Receive parameters in action controller JSON - c#

In ASP.NET MVC 5 with Entity Framework 6, I'm using a typical MVC Controller template with EF and I'm adding a custom action there.
My idea is to call this action from an AJAX call, to dynamically populate a select2 dropdown.
...
public JsonResult getWarrehouses(string name)
{
var warrehouses = from c in db.warrehouses
where c.nom_wrh.Contains(name)
orderby c.nom_wrh
select new { c.cod_wrh, c.nom_wrh} ;
return Json(warrehouses.ToList(), JsonRequestBehavior.AllowGet);
}
...
However, I don't know how to pass parameters to this, the parameter provided is always null. If I type: http://localhost:[port]/warrehouses/getWarrehouses/somestring the parameter is not received.
How I suppose to declare that action in order to receive GET parameters?
Feel free to provide an alternate solution if my approach is wrong.

The problem may be in the calling. For example:
the "name" is the name of your parameter on your Action;
$.ajax({
type: "POST",
url: #Url.Action("getWarrehouses"),
data: {
name: VALUE_TO_PASS
},
success: function (data) {
// Manipulate (data)
}

you need to use browser extensions like postman https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
they help you to make a get/post requests to getWarrehouses . with your parameters

Related

ASP.NET / jQuery : post JSON to web-service

I'm trying to post some JSON to a web service. The web-service is executed but there's no data available.
The jQuery looks like this :
var json = {"Results": results};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { TCG.QUE.processSaveButtonSucceeded(data); },
error: function (data) { TCG.QUE.processSaveButtonFailed(data); }
});
And the webservice implemented in a controller looks like this :
public HttpResponseMessage Post([FromBody]string value)
{
object o1 = Request.Content;
HttpResponseMessage r = new HttpResponseMessage(HttpStatusCode.OK);
return r;
}
If I take out the [FromBody] directive then I get a 404. If I leave it in the code is executed but the value of the value argument is null.
I thought the [FromBody] directive meant the data was contained in the Request object but if it is I can't find it .
Would appreciate any suggestions so that I can access the JSON from the client within the Post method.
UPDATE:
I just re-read this : http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api which made me wonder whether the name I was giving the JSON blog client side should correspond to the name of the argument on which the [FromBody] is applied so I changed the name of the argument from value to Results but still the value within the Post method is null.
RESOLUTION
After reading the blog post referred to by Prashanth Thurairatnam I changed my method to be like this and it works :
public HttpResponseMessage Post([FromBody]JToken jsonbody)
{
// Process the jsonbody
return new HttpResponseMessage(HttpStatusCode.Created);
}
.
Not sure what you are passing into results. Ran into this blog. You may want to give it a go. The blog talks on passing the data as JSON object/ array (you may want to try without JSON.stringify)

Error in constructed URL for getJSON method

I have the following jQuery call in the razor view.
$.getJSON('/Controller/ActionName/'+ #ViewContext.RouteData.Values["Name"] + '?Date=' + ('#StartDate').val(), function (data) {
alert(data);
});
The error in chrome browser console is that the below URL has returned no page found.
http://localhost:{portNumber}/Controller/ActionName/John?Date=9/21/2014&_=1413867422739
it is true because of the added extra token to the end of the url.
Can any one please let me know the reasons for the extra token?
I have an appropriate method in the controller and not able to figure out a solution.
The routeConfig.cs file is not changed and it has the default values to it.
Please let me know in comments if you need further information. I am not able to understand which information to furnish.
Route information:
{
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", name = UrlParameter.Optional }
);
}
Action Signature in the controller
public JsonResult ActionName(string**?** name, DateTime startDate)
{
var model = new ViewModel();
model.loadItems(name**.value**, startDate);
return Json(model.Data, **JsonRequestBehavior.AllowGet**);
}
Answer:
Made the above changes in surrounded by ** and the code worked.
Thank you for the comments and answers.
Update:
I have mentioned the default values in order to hide the unrequired information.
localhost is correct and other pages are working fine just a small part of ui which is related to this ajax call is not working.
No controller is name something else.
Can you please provide a solution for sending date values in URLS?
Change you call to (assuming your controller is really named ControllerController
$.getJSON('/Controller/ActionName/', { name: #ViewContext.RouteData.Values["Name"], startDate: $('#StartDate').val(), function (data) {..
You have a few problems here. Your default route accepts a parameter named ID but your method only has parameters name and startDate. You are not passing any parameters with those names (you are passing one for date but that does not match the method signature parameter)
Note you should not hard code the controller and action names this way. The recommend ways is
var url = '#Url.Action("ActionName", "Controller")';
var StartDate= ('#StartDate').val();
var url="/Controller/ActionName/'+ #ViewContext.RouteData.Values["Name"] + '/";
$.ajax({
url: url,
data: { Date: StartDate},
cache: false,
type: "POST",
success: function (data){
},
error: function (data){
}
});

Asp.net MVC Ajax call not calling controller method

I am making an ASP.net MVC application And I would like it so when a user clicks on a link it performs an ajax call sending data to the controller and then returning other data back to the view.
This is the method I would like to call in my controller:
public JsonResult GetImage(string url)
{
Image image = Image.FromFile(url, true);
byte[] byteImage = converter.ImageToBytes(image);
return Json(new { byteImage }, JsonRequestBehavior.AllowGet);
}
And here is the controllers location:
08983ClassLibrary\EpostASP\Controllers\CustomerController.cs
This is my Ajax Call:
$.ajax({
url: "~/Controllers/CustomerController/GetImage/",
type: 'POST',
contentType: 'application/json',
data: "url="+url,
success: function (image) {
document.getElementById("image").src = "data:image/png;base64," + image;
showImage();
}
});
When i place my breakpoints in the code I can see it hitting the ajax call then stepping over it never reaches the controller and doesnt give any errors.
Any ideas?
The main issue is here -
url: "~/Controllers/CustomerController/GetImage/",
You see, ~ is a server side literal, in other words, when you use this in a ASP.net server side path, it is replaced by the current server application folder location. This was the traditional ASP.Net way. This line has 2 errors -
This url will never work. Because its inside a string in JS and thus ASP.net does not know that it has to replace it with server path. Now comes the second error, even if ASP.net could detect and convert it, it will still not work. Because of the point I described at 2 -
Since you are using ASP.net MVC, it's not a good practice. The more conventional MVC way is to create routes and use those routes. Because in ASP.net you have the option to link to a page (.aspx, .ascx) directly. But MVC controller actions cannot be linked like that. So you have to create routes in your route config (check Global.asax) and then use that route as the url in here. BY default MVC apps will support the following format -
<host>/{controller}/action
example -
'localhost/Home/Index`
Notice that I didn't write HomeController, because by default controllers are supposed to ignore the trailing string Controller.
I hope this helped and just incase you are looking for a solution for your current situation try this (I haven't tested but it should be like this) -
$.ajax({
url: "Customer/GetImage",
type: 'POST',
contentType: 'application/json',
data: "url="+url,
success: function (image) {
document.getElementById("image").src = "data:image/png;base64," + image;
showImage();
}
});
but to be on the safe side, make sure you use -
[HttpPost]
public JsonResult GetImage(string url)
{
}
UPDATE:
the maproute (as requested in comment ) will work with any of these routes. But can also work with different routes config. Route config is very very flexible, it is just a matter to setup the routes the way it works for you. -
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"...", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"...", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"...", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Customer", action = "GetImage", id = "" } // Parameter defaults
);
routes.MapRoute(
"...", // Route name
"Customer/GetImage/{id}", // URL with parameters
new { controller = "Customer", action = "GetImage", id = "" } // Parameter defaults
);
..... //all of these mentioned route will land on the same url
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
Your ajax script says it is looking for a POST action method.
$.ajax({type: 'POST',
Have you decorated the action method with POST?
[HttpPost]
public JsonResult GetImage(string url)
{
}
Also, adjust your ajax data parameter
$.ajax({
data: {
"url": url
},
If you are using chrome you can go the developer tools -> network tab and see all the server requests being made. Hit your button and you will see it pop up and show you the response codes, headers etc. In your case it will be red and will tell you what went wrong
If you are using web api... Your method is starting with "Get" GetImages so you need to decorate the method with [HttpPost]
I have found that using fiddler is the best way to see what is going on in MVC.
Start up fiddler, run the code again and see what actually came back. Most likely (as mentioned by Yorro) is that you got a 404 error and as you have no error handling in your json call, you wont ever see the error.
$.ajax({
url: '#Url.Action("GetImage", "Customer")',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: "url="+url,
success: function (image) {
document.getElementById("image").src = "data:image/png;base64," + image;
showImage();
}
});
If using IE, and your controller is hitting the first time only add ...
$.ajax({
cache:false,
...
Some time it will work or some time not work so don't mention URL such as static "~/Controllers/CustomerController/GetImage/" please follow the dynamic way
So you will change the code snippet such as below
$.ajax({
url: "#Url.Action("GetImage", "CustomerController")",
type: 'POST',
contentType: 'application/json',
data: "url="+url,
success: function (image) {
document.getElementById("image").src = "data:image/png;base64," + image;
showImage();
}
});
hopefully this code will be resolved your problem !!

Calling method from javascript in MVC

I want to call a controller method from Javascript. I used the following code:
<input type="submit" name="button" value="Run" onclick="RunEXE"/>
I want to write the javascript to call the below function in controller.
public void Run(UserProgram userProgram)
{
SaveAndCompile(userProgram);
}
Can anyone provide me the javascript to call the function.
You can't just call a function like that. What you need to understand is that javascript runs on the client, and your function is on the server. What you need to do is make a request to the server, just like you would when loading a page, so for this you need an Action (make sure it is a POST action as we will be "posting" the request). This action can be as short as just calling the function you need:
[HttpPost]
public ActionResult RunAction(string option1)
{
//if needed, you can use the "option1" value to determine the UserProgram to pass
UserProgram userProgram = new UserProgram();
Run(userProgram);
//you can return a JSON reuslt that you can evaluate back at the client
return Json(new { #Success = true, #MyString = "a string" });
}
Then you want to use ajax to call the function from the client (javascript), for this I would recommend JQuery as it makes things much easier using post:
$.post('#Url.Action("RunAction", "MyController")',
{
option1: "some optional value"
},
function (data) {
alert("success!");
//here you have access to your JSON result via data, for example:
//data.Success = true
//data.MyString = "a string"
}
);
You can use Ajax here. jQuery ajax is very flexible and easy
Then
prepare your data to post
var myData={};// this is similar to your C# class UserProgram structure
myData.property1=value1; //etc
jQuery.ajax{(
url: '/controllerName/Run/', // or '#Url.Action("Run", "ControllerName")'
type: 'post',
data:{userProgram:myData},
success: function (data) { jQuery('#container').html(data); }
)};
or shorthand
$.post('/controllerName/Run/',{userProgram:myData}, function(result){});
Try this using JQuery:
function RunEXE() {
$.post('#Url.Action("Run", "ControllerName")',
{
userProgram: "WhatEver" //The parameter you want to pass to your action
},
function (data) {
//Code for what to do with the result.
})
};
Use the Normal AJAX method as::
On the Server side(i.e. In Controller) you are using some class/Model like 'UserProgram'
I don't know what are the Properties in that class but I have assumed it as::
public class UserProgram
{
public long ID{get;set}
public string Name{get;set}
}
this Model fields should be based on your Model that you have to pass into your AJAX code as::
var myData={ID:1,Name:"RJ"};
$.ajax{(
type: 'post',
url: '/controllerName/Run'
data:{UserProgram:myData},
success: function (data) {
$('#container').empty();
$('#container').html(data);
}
)};
To get the full description on using ajax calls in ASP.net MVC using jQuery please refer to:
http://bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/

How to call an MVC Action using only JavaScript?

I have this Kendo UI dropdownlist with a select event that is handled by a JavaScript function.
I need to call an action result from a controller that runs a LINQ query to populate a Kendo UI grid on my page. My problem is the only way I can find to handle this even is with JavaScript and I have been unable to figure out how to call my action result from my controller from the JavaScript event function.
This is what the DropDownList looks like...
#(Html.Kendo().DropDownList()
.Name("Options")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Policies Not Archived",
Value = "1"
},
new SelectListItem() {
Text = "View All Policies",
Value = "2"
},
new SelectListItem() {
Text = "Filter Policies",
Value = "3"
}
})
.Events(e =>
{
e.Select("select");
})
)
and my JavaScript event handler that needs to call the action result
function select(e) {
}
and depending on the selection an ActionResult like this,
public ActionResult ViewAllPolicies()
{
//mycode
}
see this post
var url = '#Url.Action("ViewAllPolicies","YourController")';
$.ajax({ url: url, success: DataRetrieved, type: 'POST', dataType: 'json' });
in controller
public ActionResult ViewAllPolicies()
{
//Should return json format
}
url – this is the URL where request is sent. In my case there is
controller called contacts and it has action calles
ListPartiesByNameStart(). This action method takes parameter
nameStart (first letter of person or company). success – this is the
JavaScript function that handles retrieved data. You can write there
also anonymous function but I suggest you to use functions with names
because otherwise your code may get messy when functions grow. type –
this is the type of request. It is either GET or POST. I suggest you
to use POST because GET requests in JSON format are forbidden by
ASP.NET MVC by default (I will show you later how to turn on GET
requests to JSON returning actions). dataType – this is the data
format that is expected to be returned by server. If you don’t assign
it to value then returned result is handled as string. If you set it
to json then jQuery constructs you JavaScript object tree that
corresponds to JSON retrieved from server.
Instead of returning json, you can also return a PartialView and in the .done function grab an element and replace it with the results from the partial view. PartialView actions basically return a fragment of HTML, and so you can just stuff that anywhere you want on the page:
$.ajax({
url: urlToPartialViewAction,
type: 'POST',
dataType: 'JSON',
data: '123'
})
.done(function (result) {
$('#someDivPlaceholder').replaceWith(result);
});
You could have something like a link or grey div and wire up to it's click event and then call this, the link might say "View Receipt" and when you click it you call an action that returns a partial view with the receipt, and so when they click it the div/link is replaced with the result. Kind of like the "View More Comments" links you see on social sites.
Note that you can't have a partial view by itself, it must be called through an action
public PartialViewResult _GetReceipt(string id)
{
ReceiptViewModel vm = //query for receipt data
return PartialView(vm);//render partial view and return html fragment
}
Once the select function executes, you need to make an AJAX call back to your Controller. You can use jQuery.ajax() (a wrapper for the most common AJAX operations) in the select function,
function select(e) {
var url = '#Url.Action("ViewAllPolicies", "PolicyController")';
var selectedPolicy = $('#Options').val(); // The option selected
$.ajax({
url: url,
type: 'POST',
dataType: 'JSON',
data: selectedPolicy
})
.done(function (data) {
// Display the data back from you Controller
});
}
You can look at the Kendo site for more info on how the DropDownList works.

Categories