Tips! ASP.NET MVC – JavaScriptSerializer – 3 Questions and 3 Answers

Thanks to Darin Dimitrov (MVP)  for answering questions in very details!

Test Project Download ~

  • git clone: git@github.com:michaelsync/Michael-Sync-s-blog-sample.git
  • AjaxJsonTest

Scenario

I have the following model, view and controller.

Model

public class Person {
 public string Name;// { get; set; }
 public string Occupation { get; set; }
 public int Salary { get; set; }
 public int[] NumArr { get; set; }
}

View

<input id="Test" type="button" value="Test" />

@section Javascript{
<script type="text/javascript">// <![CDATA[
 $(function () {
 $("#Test").click(function () {
 var data = { Name: "Michael Tom", Occupation: "Programmer", Salary: 8500, NumArr: [2,6,4,9] };
 var url = "Home/GetJson";
 $.ajax({
 url: url,
 dataType: "json",
 type: "POST",
 data: data,
 traditional: true,
 success: function (result) {

}
 });

});
 });
// ]]></script>
}

Controller

public class HomeController : Controller
 {
 public ActionResult Index()
 {
 return View();
 }

public JsonResult GetJson(Person person) {

return Json(......);
 }
 }

Questions

1) Why can’t we use the public field instead of properties in Model? 

Because the model binder works only with properties. It is by design. Normally fields should be private in your classes. They are implementation detail. Use properties to expose some behavior to the outer world.

2) If I changed the type of NumArr property to List<int> then it doesn’t work. How can we use List instead of the int[]? I know I’m passing the array from JS. Can we pass List<T> from JS as well?

It should work. No matter whether you use List<int>, IEnumerable<int> or int[], it’s the same and it works. What wouldn’t work is if you wanted to use a collection of some complex object like for example List<SomeComplexType> (see my answer below for a solution to this).

3) I’m using “traditional: true” in Javascript code block of View because serialization doesn’t work with “traditional: false”. Does ASP.NET MVC’s serializer support only old version?

Yes, the traditional parameter was introduced in jQuery 1.4 when they changed the way jQuery serializes parameters. The change happened to be non-compatible with the standard convention that the model binder uses in MVC when binding to lists.

So download a javascript debugging tool such as FireBug and start playing. You will see the differences in the way jQuery sends the request when you set this parameter.

All this being said I would recommend you to send JSON encoded requests to your controller actions. This will work with any complex objects and you don’t have to ask yourself which version of jQuery you are using or whatever because JSON is a standard interoperable format. The advantage of a standard interoperable format is that no matter which system you use, you should be able to make them talk the same language (unless of course there are bugs in those systems and they do not respect the defined standard).

But now you could tell me that application/x-www-form-urlencoded is also a standard and inetroperable format. And that’s true. The problem is that the model binder uses a convention when binding the name of the input fields into properties of your models. And this convention is far from something being interoperable or industry standard.

So for example you could have an hierarchy of models:

public class Person
{
 public string Name { get; set; }
 public string Occupation { get; set; }
 public int Salary { get; set; }
 public List SubObjects { get; set; }
}

public class SubObject
{
 public int Id { get; set; }
 public string Name { get; set; }
}

You could imagine any complex hierarchy you like (at the exception of circular references which are not supported by the JSON format). and then:

var data = {
 name: "Michael Tom",
 occupation: "Programmer",
 salary: 8500,
 subObjects: [
 { id: 1, name: 'sub 1' },
 { id: 2, name: 'sub 2' },
 { id: 3, name: 'sub 3' }
 ]
};

$.ajax({
 url: "Home/GetJson",
 type: "POST",
 data: JSON.stringify({ person: data }),
 contentType: 'application/json',
 success: function (result) {

}
});

We set the Content-Type request HTTP header to application/json to indicate the built-in JSON value provider factory that the request is JSON encoded (using the JSON.stringify method) and it will parse it back to your strongly typed model. The JSON.stringify method is natively built into modern browsers but if you wanted to support legacy browsers you could include the json2.js script to your page.

Reference: