JSON is a data exchange format used for sending the information between the web browser and the web server.Today AJAX is a commonly used in most of the web sites.AJAX can improve the performance of the page and is useful in creating rich internet applications.The information exchanged using AJAX is used to partially update the web page instead of re rendering the entire web page.This results in not only better experience for the end user but also since the entire page is not returned in an AJAX request it also reduces the required bandwidth and hence improves in better performance.
Instead of returning the HTML fragments we can return just the data which will further improve the performance of the web page.But the data which is exchanged between the web browser and the web server should be serialized in a specific format.
So to return the data from the web server and consume it in a web browser we need some common data exchange format which is understood by both the web browser and the web server.JSON is such a data exchange format.
JSON stand for Java Script Object Notation and it is used to represent data which can be understood by both the machine and humans.Unlike XML it is easy to understand by humans.We can represent an object is JSON as:
{"employees":[ {"Name":"Alan", "Address":"France"}, {"Name":"Smith", "Address":"Brazil"}, ]}
JSON support in MVC
MVC provides the JSON helper method which can be used to serialize the CLR or .NET objects into json format.Json helper method expects few arguments such as:
- data this represents the CLR object that needs to be serialized to JSON.
- JsonRequestBehavior Enumeration that specifies whether HTTP Get requests are allowed.
- ContentEncoding Represents the content encoding.The default is UTF-8 for JSON data.
So we can use the json helper method as:
return Json(object,JsonRequestBehavior.AllowGet);
The above statement will create a json object from the CLR object JsonRequestBehaviour.AllowGet will allow the method to be called using the HTTP Get requests.
In the following example we are fetching the data in json format on the button click event.Once the data is fetched from the server we are displaying it in
an html table
Following is the class whose object we will be returning from the server in JSON format.
public class Employee { public string Name { get; set; } public string Address { get; set; } public string PhoneNo { get; set; } public string Country { get; set; } }
We have defined the Employees controller below.In the GetEmployees() method we are returning a list of Employee objects which we will be displaying in the web page
public class EmployeesController : Controller { public ActionResult Home() { return View(); } [HttpPost] public JsonResult GetEmployees() { Employee[] emps = { new Employee { Name = "Mark",Address="Address1",PhoneNo="XYZ",Country="UK" }, new Employee { Name = "John",Address="Address2",PhoneNo="XYZ",Country="Germany" }, new Employee { Name = "Lisa",Address="Address3",PhoneNo="XYZ",Country="UK" }, new Employee { Name = "Mike",Address="Address4",PhoneNo="XYZ",Country="Australia" } }; return Json(emps,JsonRequestBehavior.AllowGet); } }
We have defined the Employees view as below.We are making an ajax call to the GetEmployees() method on button click event.We are returning Employee objects from the GetEmployees() method using the JSON helper method.We are looping through the collection of Employee objects and appending to a variable.We are then appending the contents of this variable to an html table.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#btnSubmit").bind("click", function () { $.ajax({ type: "POST", url: "Employees/GetEmployees", traditional: true, contentType: 'application/json; charset=utf-8', success: function (data) { if (data) { var len = data.length; var txt = ""; if (len > 0) { for (var i = 0; i < len; i++) { if (data[i].Name && data[i].Address) { txt += "<tr><td>" + data[i].Name + "</td><td>" + data[i].Address + "</td></tr>" + "<td>" + data[i].PhoneNo + "</td>" + "<td>" + data[i].Country + "</td></tr>"; } } if (txt != "") { $("#EmployeesTable").append(txt); alert(txt); } } } }, error: function (data) { alert("error"+data) } }); }); } ); </script>
The html for the view is defined as below.We are just adding a button to the view on the click of which we are making the ajax call the controller action method.
<input id="btnSubmit" type="button" value="Update" /> <table id="EmployeesTable" width="300px;"> <tr> <td style="color:green;width:50px" >Name </td> <td style="color: green; width: 50px">Address </td> <td style="color: green; width: 50px">PhoneNo </td> <td style="color: green; width: 50px">Country </td> </tr> </table>
In the above sript we are making an ajax reuest to the GetEmployees() action method of the Employees controller.In the success callback method we are updating the html table with the returned data.The above view is rendered as:
Fetching json data using jquery ajax in MVC can be easily implemented using the Json helper method in mvc .As the CLR is object is automatically created by the helper method we just need to retrieve the object properties in javascript.
While creating web applications of today it is important to consider the performance of the application.One of the important factor for improving the performance is reducing the required bandwidth.So its important to avoid fetching the unnecessary data such as html with every request.By using json we can just request the necessary data from the server and update the contents without updating the html.
Prakash says
I read few of your articles. They are very useful to understand concept and implementation.
You did a fantastic job.
ashish shukla says
Thanks,I am glad that the article is helpful for understanding the concept.