I have a web page that is using JQuery to communicate with the backend. I have some POST actions. However, I now have a GET action and I've noticed that the parameter values passed to it are null. My POST actions work just fine. I can't figure out why.
From my .html file, I have the following JQuery query:
var vm = { emailAddress:"[email protected]" };
$.ajax({
url: "/myService/myAction",
type: "GET",
data: JSON.stringify(vm),
contentType: "application/json",
success: myAction_Succeeded,
error: myAction_Failed
});
In my controller, I have:
public class MyServiceController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult MyAction(string emailAddress)
{
return Json(new { address:emailAddress });
}
}
My route is setup as follows:
context.MapRoute(
"MyAction",
"myService/{controller}/MyAction",
new { controller = "MyService", action = "MyAction" }
);
I have a hunch that I'm missing something in my route. But I'm not sure what it is. I followed the same syntax I used with my POST actions. Parameters with those actions work just fine. But the parameters with my GET actions, like the one above, have null values. My question is, what am I doing wrong and what if I need to pass multiple parameters?
Thank you so much for your help!
The JsonValueProviderFactory that allows you to send JSON requests to controller actions in ASP.NET MVC 3 works with POST requests. For GET requests you could use a standard request:
var vm = { emailAddress:"[email protected]" };
$.ajax({
url: "/myService/myAction",
type: "GET",
data: vm,
success: myAction_Succeeded,
error: myAction_Failed
});
Or if you want to send JSON requests modify type: 'POST'
in your AJAX request. Obviously in this case you will have to remove the HttpVerbs.Get
attribute from your controller action which currently constrains it to only GET requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With