I am using MVC3 and that i know MVC3 support binding JSON literal to Action parameter. But i can’t do it successfully;
I have a class name Tag
public class Tag
{
public int tagId { get; set; }
public string tagName { get; set; }
}
An Action on controller called Tag
[HttpPost]
public ActionResult Tag(Tag tag)
{
// Here will be codes...
return Json(new { success = 0 });
}
Javascript code that send js object as JSON to my action
var tag ={tagId:5,tagName:"hello"};
$.ajax({
url: "/image/tag",
type: "POST",
data: $.toJSON(tag),
success: function (r) {
if (r.success == 1) {
window.location = r.redirect;
}
}
Post Data that I see in Firebug Net tab
{"tagId":5,"tagName":"hello"}
Parameter name tag in Tag Action is not null but has values O for tagId and null for tagName.
What the problem in here?
You need to set the content type of the request to
application/json:Ah, and you don’t need to have your Tag model properties start with a lowercase letter:
Remark 1: The
JavaScriptSerializerclass that ASP.NET MVC 3 uses behind the scenes is capable of properly handling this.Remark 2: In your
Tagaction you seem to be returning the following JSON:{"success":0}whereas in your success AJAX callback you seem to be using somer.redirectproperty which doesn’t exist.Remark 3: Avoid naming your controller actions the same way as your view models. Normally action names should represent verbs (like
List,Save,Delete, …) whereas view models represent resources (TagModel, …).