Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Parameters from JQuery to Controller Action in ASP.NET MVC 3

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!

like image 693
JQuery Mobile Avatar asked Feb 11 '12 13:02

JQuery Mobile


1 Answers

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.

like image 51
Darin Dimitrov Avatar answered Oct 28 '22 10:10

Darin Dimitrov