03 November 2013

Simple jQuery getJSON Example in ASP.NET MVC


First off, what is JSON? It is an alternative to XML as a way of sending information from one device to another. Now, how do we use it as a mediator between a database and a web page in ASP.NET MVC 4?
Well, it is going to be simple two step process as mentioned below:
1. Write a controller that contains a method that is called when a client requests a web page from the server.
2. Write a view that is linked to the controller method, and which generates the markup that is returned to the client.

The controller method will usually collect some data from some other source, such as a database or some other C# code (which is usually part of the Model in MVC). This data is then packaged up, possibly in a C#/JSon object, and sent to the View, where the View formats the data and generates the HTML which is interpreted by the browser.
Basically what happens is this:
1.    Client requests a web page.
2.    Controller method is called to process this request.
3.    The corresponding View is returned to the browser.
4.    The View contains some JavaScript code that makes another request to the server, this time asking for some data in JSON format.
5.    A different Controller method from that called in step 2 is called to generate the JSON, which is returned to the browser.
6.    The JavaScript code processes the JSON and generates some HTML which is displayed (JSON is not meant to be displayed as raw data by the browser; rather, it is retrieved by the browser and then processed on the client side before it is displayed)

In this post, I will create a very basic and simple example demonstrating jQuery's getJSON method using ASP.NET MVC.
First up, I create an empty MVC project with one Controller. The code for this controller is shown below. For simplicity, the data model is also stored here and we create the data on fly. In a production application, this will be separated   using multiple layers and the data, of course, would come from the database.
   1:  <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   2:      <script type="text/javascript">
   3:          $(document).ready(function () {
   4:              $('#btnGetCustomers').click(function () {
   5:                  $.getJSON("/Json/GetJsonData", null, function (data) {
   6:                      var div = $('#ajaxDiv');
   7:                      div.html("<br/> " + "Customeres received from server: " + "<br/>");
   8:                      $.each(data, function (i, item) {
   9:                          printCustomer(div, item);
  10:                      });
  11:                  });
  12:              });
  13:          });
  14:   
  15:          function printCustomer(div, item) {
  16:              div.append("<br/>" + "FName: " + item.FirstName + ", LName: " + item.LastName);
  17:              });
  18:          }
  19:      </script>
  20:   
  21:      <input id="btnGetCustmers" type="button" value="Get Customers" />
  22:      <div>
  23:          <div id="ajaxDiv">
  24:          </div>
  25:      </div>
  26:   
  27:  $(document).ready(function () {
  28:      $('#save').click(function () {
  29:          var person = {
  30:                          Id: 100,
  31:                          Name: $('#Name').val(),
  32:                          Age: $('#Age').val(),
  33:                          PhoneNumber: $('#PhoneNumber').val()
  34:                      };
  35:          $.ajax({
  36:              url: '/Home/CreatePerson',
  37:              type: "POST",
  38:              data: JSON.stringify(person),
  39:              dataType: "json",
  40:              contentType: "application/json; charset=utf-8",
  41:              success: function (result) {
  42:                  $('#message').html('Person Saved' + result).fadeIn();
  43:              },
  44:              error: function () {
  45:                  $('#message').html('Error Occurred').fadeIn();
  46:              }
  47:          });
  48:          return false;
  49:      });
  50:  });
C# code 

   1:       public ActionResult Index()
   2:          {
   3:              return View();
   4:          }
   5:   
   6:          public JsonResult GetJsonData()
   7:          {
   8:              var Customer = new List<Customer>
   9:                                {
  10:                                    new Customer{Id = 1, FirstName = "John", 
  11:                                        LastName = "Randy", PhoneNumber = "(614)370-0220"},
  12:                                                                                                          
  13:                                    new Customer{Id = 2, FirstName = "Sheila", 
  14:                                        LastName = "Wood", PhoneNumber = "(614)370-0200" }};
  15:   
  16:              return Json(Customer, JsonRequestBehavior.AllowGet);
  17:   
  18:          }
  19:   
  20:      }

No comments: