Passing parameters from jQuery to controller action in ASP.NET MVC 3

I have a webpage using jQuery to communicate with the backend. I have some POST actions. However, I now have a GET action, and I noticed that the parameter values ​​passed to it are zero. My POST actions are working fine. I can’t understand why.

From my .html file, I have the following jQuery query:

var vm = { emailAddress:" someone@somewhere.com " }; $.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 configured 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 that I used with my POST actions. Parameters with these actions work fine. But the parameters with my GET actions, as above, have zero values. My question is: what am I doing wrong, and what if I need to pass several parameters?

Thank you so much for your help!

+6
source share
1 answer

JsonValueProviderFactory, which allows you to send JSON requests to controller actions in ASP.NET MVC 3, works with POST requests. For GET requests, you can use the standard request:

 var vm = { emailAddress:" someone@somewhere.com " }; $.ajax({ url: "/myService/myAction", type: "GET", data: vm, success: myAction_Succeeded, error: myAction_Failed }); 

Or if you want to send JSON requests, change type: 'POST' in the AJAX request. Obviously, in this case you will have to remove the HttpVerbs.Get attribute from your controller action, which currently restricts it to GET requests only.

+4
source

Source: https://habr.com/ru/post/908211/


All Articles