MVC 3 - JSON serializer

Michael Sync picture Michael Sync · Apr 2, 2012 · Viewed 9.7k times · Source

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 type="button" id="Test" value="Test" />

@section Javascript{
<script type="text/javascript">
    $(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(......);
        }
    }

Based on those code above, I like to ask three questions.

  1. If we use public field instead of properties, the serializer doesn't serialize the json object to C# model so I always get null for "Name" field in controller. Why does it happen like that?

  2. If I changed the type of NumArr property to List 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 from JS as well?

  3. I'm using "traditional: true" in Javascript code block of View because serialization doesn't work with "traditional: false". I heard that jQuery has three version of Json serializer. ASP.NET MVC's serializer supports only old version. Is it true?

3.1. If it's true, I like to know when you are going to get the latest version of MVC's serializer that supports jQuery's latest version.

3.2. Is there any way to register a custom Javascript Serializer just like we can register custom view engine? My friend suggested me that I can register custom value provider or custom model binder and use custom JS serializer in my custom value provider /model binder.

Thanks in advance. Please feel free to let me know if you are not clear about my questions. Thanks!

Answer

Darin Dimitrov picture Darin Dimitrov · Apr 2, 2012

1) If we use public field instead of properties, the serializer doesn't serialize the json object to C# model so I always get null for "Name" field in controller. Why does it happen like that?

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 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 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". I heard that jQuery has three version of Json serializer. ASP.NET MVC's serializer supports only old version. Is it true?

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<SubObject> 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.