Skip to main content

Asp.net 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();
  }
   
  [HttpPost]
  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() };

        $.ajax({
            url: "/Category/Create",
            data: JSON.stringify(CategoryName),
            contentType: "application/json; charset=utf-8",
            success: function (mydata) {
                $("#message").html(mydata["message"]);
            },         
            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() 
   {
     RegisterRoutes(RouteTable.Routes);
     ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
   }

Comments

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

    ReplyDelete
  2. Good posting. Keep it up!

    ReplyDelete
  3. what is the purpose to use JSON Binding ?

    ReplyDelete

Post a Comment

Popular posts from this blog

Asp.net mvc razor render partial view using ajax helper

This is the extension to my blog in which I demonstrated rendering of the partial view using jquery Ajax . I want to demonstrate here yet another way by which partial view can be rendered without page refresh. Here is the implementation. Step 1: I will again be using DisplayData class in my demo. Here is it. public class DisplayData { public int ID { get; set; } public DisplayData(int ID) { this.ID = ID; } } Step 2: Create a PartialDemo page @model IEnumerable<MvcApplication5.Models.DisplayData> @{ ViewBag.Title = "PartialDemo"; } @Ajax.ActionLink("Click 1", "PartialDemo", "PartialDemo", new {Data= "1" }, new AjaxOptions { UpdateTargetId = "rsvpmsg" }) @Ajax.ActionLink("Click 2", "PartialDemo", "PartialDemo", new {Data= "2" }, new AjaxOptions { UpdateTargetId = "rsvpmsg" }) <div id="rsvpms...

Asp.net mvc razor render partial view using jquery Ajax

I will going to demonstrate how we can render PartialViews using Jquery Ajax. I will be clicking an a href link ,then I will be calling the controller through jquery Ajax which will fill the partialview for a really nice user experience. Step 1: First of all we will be creating an DisplayData class for the use for this example in the model. public class DisplayData { public int ID { get; set; } public DisplayData(int ID) { this.ID = ID; } } Step 2: We will create a Clicks page and write the following code on it. Specially note empty here which will going to empty and then fill partialview with new records. $(document).ready(function () { $('.msg').click(function () { var id = this.id; $.ajax({ url: "/Category/Display", data: { data: id }, success: function (mydata) { $("#link").empty().appe...

Dotnetnuke Inter-module communication (IMC) simplified on version 06.00.02 with c#

Few days ago I developed a module in which I used IMC which really interested me so I decided to write about it. I will try to explain in this post everything that is necessary to make IMC work in the modules. What is Inter Module Communication? As the name implies if you want to communicate or in other words send data from one module to another IMC is one way of doing it. I will be using module A and module B as the names in my post. An Observation: One thing I observed while playing around with it that if module A is on page 1 and module B is on page 2 then the data doesn't get passed. If both the modules are on the same page then only the data get passed. Example: The basic exercise that I will be performing is to take input from the textbox in Module A and display it in label in Module B. 1) You will be using IModuleCommunicator and IModuleListener interfaces to make this communication works. You will be implementing IModuleCommunicator in the class in the modul...