Reputation: 1570
I have no problems processing jQuery GET requests in a controller, however I cannot get any form data to POST. The client snippet
$.post(url,{name:"John"},function(result){
//process result
});
combined with a controller,
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(string name)
{
return Json("Success!");
}
will result in a NULL value for the name parameter when inspected inside the action method, whereas I expected name to be mapped to the method parameter. Also all other objects (Request.Form), etc. in this context seem to be NULL. I can do this with a $.get
, but I think I am supposed to do any operations with side-effects with POSTs. I am using ASP.NET MVC 1.0, jQuery 1.2.6 and Internet Explorer 7.
Thanks!
Update: see my answer below and humble apologies
Upvotes: 3
Views: 5721
Reputation: 1570
Sorry guys, I had a $.ajaxSetup entry in the page which overrided the default contentType to application/json.
When using the default contentType as follows:
$.ajax({ url,
type: "POST",
contentType: "application/x-www-form-urlencoded",
success: function(result) { alert(result); },
data: { name: "John" }
});
It works because processData is true by default which means the data entry with the JSON object will be parsed into a string (data: "name=John" also works).
Sorry for wasting your time :) and thanks to Mark for the suggestion on passing JSON objects, ill do that next cause it seems very cool.
Upvotes: 6
Reputation: 384
I believe your code should work, is your URL correct and your routes setup correctly? In addition you could always fire up Fiddler to see exactly what your request to the server is and if you are passing the correct items.
Upvotes: 2
Reputation: 6633
It isn't so simple as making a json object and throwing it at an action.
Start from here. People have written small scripts that get the JSON object dressed and ready for an action to read it in and map it to properties or arguments.
Upvotes: 1
Reputation: 2918
Could it be that the Save(string name) method is expecting stringified JSON? Try this:
$.post(url,
"{'name':'John'}", function(result){
});
Upvotes: 1