.NET life

HUGON Jérôme
Microsoft Certified Technology Specialist Microsoft Certified Application Developer Microsoft Certified Professional

JSON Binding Support

MVC 3

Category MVC 3  | Publication Date : 4/2/2011

With the JSON Binding Support in MVC 3, you can send JSON encoded data to the actions and the model will be automatically bound to parameters. This allows the connection between server and client data by sending and receiving JSON those above.

 

Consider the following view that displays a creation fom based on TestModel model with two properties: Title and Description:

MVC3 - JSON Support - 1

I modified the Create button of type Submit for a link :

<a id="Save" href="#">Create</a>

The Click event of this link is binded to the following function which encapsulate data from the form and then send it, JSON encoded, to our action:

<script type="text/javascript">
    $('#Save').click(function () {
        var test = {
            Title: $('#Title').val(),
            Description: $('#Description').val()
        };
        $.ajax({
            url: '/Test/SupportJSON',
            type: "POST",
            data: JSON.stringify(track),
            datatype: "json",
            contentType: "application/json; charset=utf-8",
            success: function () { $('#Result').html('OK'); },
            error: function () { $('#Result').html('ERROR'); }
        });
        return false;
    });
</script>

On the server side, the action target of the request does nothing specific:

[HttpPost]
public ActionResult SupportJSON(TestModel model)
{
    return View();
}

This action accepts a model of type TestModel as the only parameter. Without write more server side, MVC 3 will be able to link the JSON encoded data received and the type parameter of the action target:

MVC3 - JSON Support - 2

MVC3 - JSON Support - 3


Related articles

TechDays 2011 - What's new in ASP.NET MVC 3

MVC 3

Category MVC 3  | Publication Date : 4/16/2011