Asp.Net MVC 3 JSON Model Binding not working

I am using MVC3 and know that MVC3 supports JSON literal binding to Action parameter. But I cannot do it successfully;

I have a class name Tag

public class Tag { public int tagId { get; set; } public string tagName { get; set; } } 

Action on a controller named Tag

  [HttpPost] public ActionResult Tag(Tag tag) { // Here will be codes... return Json(new { success = 0 }); } 

Javascript code that sends a js object as JSON for 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; } } 

Publish the data that I see on the Firebug Net tab.

 {"tagId":5,"tagName":"hello"} 

The parameter name tag in the tag action is not null, but it has O for tagId and null for tagName. What is the problem?

+7
source share
1 answer

You need to set the content type of the application/json request:

 $.ajax({ url: '/image/tag', type: 'POST', contentType: 'application/json; charset=utf-8', data: $.toJSON(tag), success: function (r) { if (r.success == 1) { window.location.href = r.redirect; } } }); 

Oh, and you donโ€™t need the tag model properties to start with a lowercase letter:

 public class Tag { public int TagId { get; set; } public string TagName { get; set; } } 

Note 1: The JavaScriptSerializer class, which uses ASP.NET MVC 3 behind the scenes, is able to handle this correctly.

Note 2: In your Tag action, you seem to return the following JSON: {"success":0} , while in your AJAX callback you seem to be using some kind of r.redirect property that does not exist.

Note 3: Avoid naming your controller actions in the same way as your viewing models. Typically, action names should represent verbs (e.g. List , Save , Delete , ...), while view models represent resources ( TagModel , ...).

+18
source

All Articles