Sunday, 27 March 2011 mvc 3 built in json model binding

One of the things in mvc3 that recently caught my eyes is built in json model binding support which I have recently used in my project and want to write about it today. JsonValueProviderFactory Class which do all the stuff regarding json model binding is now built-in in mvc 3 which was not in mvc2. To use it in mvc2 you have to register the JsonValueProviderFactory class in global.asax after referencing Microsoft.Web.Mvc from Mvc Futures Library . Here how the thing goes in mvc3

Model Class

  public class Category
     public string CategoryName { get; set; }
The Controller
  public ActionResult Create()
     return View();
  public ActionResult Create(Category category )
     string Cat = category.CategoryName; 
     var data = new { message = "ok" };
     return Json(data); 

The View
$(document).ready(function () { 
    $('#save').click(function () {

        var CategoryName = { CategoryName: $('#CategoryName').val() };

            url: "/Category/Create",
            data: JSON.stringify(CategoryName),
            contentType: "application/json; charset=utf-8",
            success: function (mydata) {
            type: "POST",
            datatype: "json"
        return false;

@using (Html.BeginForm()) { @Html.ValidationSummary(true)
@Html.EditorFor(model => model.CategoryName) @Html.ValidationMessageFor(model => model.CategoryName)

For Model binding to work in Mvc2 Add JsonValueProviderFactory
in Global.asax after referencing Microsoft.Web.Mvc
   protected void Application_Start() 
     ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());


  1. Very cool - thanks for posting this. Very clear explanation.

  2. Good posting. Keep it up!

  3. what is the purpose to use JSON Binding ?