19 November 2013

Json object from MVC view to controller as Parameter

JSON (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. When working together with jQuery and ASP.NET MVC in building web applications, it provides an efficient mechanism to exchange data between the web browser and the web server. This includes built-in JSON binding support that enables action methods to receive JSON-encoded data and model-bind it to action method parameters. To see this feature in action, consider the client-side jQuery below.


   1:      $('#Save').click(function () {
   2:          var customer = {
   3:              Name: $('#Name').val(),
   4:              Code: $('#Code').val()
   5:          };
   6:          $ajax({
   7:              url: 'Custoer/Save',
   8:              type: "POST",
   9:              data: JSON.stringify(customer),
  10:              dataType: "json",
  11:              contentType: "application/json",
  12:              success: function () {
  13:                  $('#message').html('Data Saved').fadeIn();
  14:              },
  15:              error: function () { $('#message').html('Operation failed').fadeIn(); }
  16:          })
  17:          return fasle;
  18:      });

Next is to consume this data at the server side, i.e. at MVC control, create a model class with exact number of fields to hold the desterilized data.And then have a action method in your controller method.


   1:      public class Customer
   2:      {
   3:          public string Name { get; set; }
   4:          public string Code { get; set; }
   5:      }
   6:      public ActionResult Save(Customer jsonCustomerData)
   7:     {
   8:          bool result = true;
   9:          Customer customerData;
  10:          JavaScriptSerializer jss = new JavaScriptSerializer();
  11:          customerData = jss.Deserialize<Customer>(jsonCustomerData);
  12:          // Logic to save data
  13:          return Content(result.ToString());
  14:     }

As you see above sample server side we have an action which accepts strongly-typed Customer object as a parameter. Serialized json object will be routed here. That means ASP.NET MVC 3 automatically bind the incoming JSON post values to the .NET Customer type on the server – without you having to write any custom binding or marshalling logic. Now inside the method you may desterilize this data using JavaScriptSerializer which is available in System.Web.Script.Serialization library.

No comments: