Shravan Kumar Kasagoni

Skip Navigation
JSON Binding Support in ASP.NET MVC 3

JSON Binding Support in ASP.NET MVC 3

 /  3 responses

This article is about how to send json object to asp.net controller action method & bind it to strongly typed .NET object. We have many mechanism to do this.

  1. Bind json encode string to System.Object, write logic to decode the json encoded string & bind it to Model or ViewModel.
  2. Write custom model binder with lot of efforts(validations , serializing values, etc.)

ASP.NET MVC 2 provides a easy way to do this using ASP.NET MVC 2 Futures library.

ASP.NET MVC 2 Futures library provides JsonValueProviderFactory to this job. We should register JsonValueProviderFactory in Global.asax Application_Start() method.

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}

JsonValueProviderFactory is available in Microsoft.Web.Mvc.dll for ASP.NET MVC 2. we should add the reference of Microsoft.Web.Mvc.dll to our project to use JsonValueProviderFactory. Now if we send json object from JavaScript to asp.net mvc controller action method json object can directly bind to strongly typed .net object (model or viewmodel in asp.net mvc).

In ASP.NET MVC 3 we need not worry about all this steps, ASP.NET MVC 3 has built in JSON Binding Support, JsonValueProviderFactory is registered by default ASP.NET MVC 3. if we send any json object from JavaScript to asp.net mvc controller action method json object can directly bind to strongly typed .net object (model or viewmodel in asp.net mvc) automatically, provider will take care validations, serializing, de-serializing values etc.

Look at this example:

I have person model object, I want to save Person model object in database.

  • Create new ASP.NET MVC 3 empty solution
  • Add a HomeController to solution, Add Action Method named CreatePerson().
using System.Web.Mvc;
namespace JsonBindingExample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult CreatePerson()
        {
            return View();
        }
    }
}
  • Add Person model object to model folder in solution
namespace JsonBindingExample.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Age { get; set; }
        public string PhoneNumber { get; set; }
    }
}
  • Create a View
    • Right click on CreatePerson() Action Method click on Add View, It will display Add View dialog.
    • In Add View dialog, enter View name, Choose View Engine (razor), select strongly-typed view, in strongly-typed view choose the Person Model class, In Scaffold template dropdown choose view, click on add.
addview
  • Now MVC will generate CreatePerson view in ~/Views/Home/ folder as CreatePerson.cshtml
@model JsonBindingExample.Models.Person
@{
    ViewBag.Title = "Create Person";
}
<h2>Create Person</h2>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/json2.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MyScript.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Person</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Age)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.PhoneNumber)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PhoneNumber)
            @Html.ValidationMessageFor(model => model.PhoneNumber)
        </div>
        <p>
            <input id="save" type="button" value="Save Person" />
        </p>
        <div id="message">
        </div>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
  • Add JavaScript file named MyScript.js with following code & add MyScript.js to CreatePerson.cshtml view.
$(document).ready(function () {
    $('#save').click(function () {
        var person = {
                        Id: 100,
                        Name: $('#Name').val(),
                        Age: $('#Age').val(),
                        PhoneNumber: $('#PhoneNumber').val()
                    };
        $.ajax({
            url: '/Home/CreatePerson',
            type: "POST",
            data: JSON.stringify(person),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                $('#message').html('Person Saved' + result).fadeIn();
            },
            error: function () {
                $('#message').html('Error Occurred').fadeIn();
            }
        });
        return false;
    });
});

Above JavaScript is fired when you click on Save Person Button, I am creating JavaScript person object by retrieving values on form using jQuery & calling CreatePerson action method in HomeController asynchronously using $.ajax() method in jQuery & send person object as parameter.

In order to convert JavaScript object into json encoded string i am using JSON.stringify() method, which is available in json2.js, we should json2.js also to view.

  • Add CreatePerson(Person person) with [HttpPost] attribute to controller with Person object as parameter.
[HttpPost]
public ActionResult CreatePerson(Person person)
{
    return Json("ok");
}

We have done with required coding lets see the example in action, run the application, go to CreatePerson View. Enter value, Click on Save, before that add a breakpoint in Visual Studio to CreatePerson(Person person) action method.

createperson
person

Now json object is directly bind to C# Person object , now we use person object for storing in database or any required action as you wish.

Download Source Code Here

Write a response

Your email address will not be published. Required fields are marked *

All code will be displayed literally.

Discussion

Close Bitnami banner
Bitnami