JsonResult In ASP.NET MVC


MVC controller returns many types of output to the view according to the data we need for the application. In this article we will learn about JsonResult type of MVC . So instead of going into the depth on the subject, let us start with its practical implementation.
To know more about the Action result types please refer my previous article 
 What is ActionResult ?

ActionResult is the abstract class for showing the output to the client in various formats as in the result view returned by the controller. The ActionResult is defined in the controller and the controller returns to the client (the browser).
What is JsonResult ?

JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).

 In this article we will learn about JsonResult by taking scenario  to bind view using the JSON Data . So let's see step by step.
Step 1 : Create an MVC application
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".

  2. "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.

  3. Choose MVC empty application option and click on OK
Step 2 : Create Model Class

Right click on Model folder in the created MVC application, give the class name employee or as you wish and click OK.
  1. public class Employee  
  2. {  
  3.      public int Id { getset; }  
  4.      public string Name { getset; }  
  5.      public string City { getset; }  
  6.      public string  Address { getset; }  

Step 3: Add controller class.

Right click on Controller folder in the created MVC application; give the class name. I have given class name Home and clicked on OK.

  1. public class HomeController : Controller    
  2. {    
  3.     // GET: Home    
  4.     public ActionResult Index()    
  5.     {    
  6.     return View();    
  7.     }    
  8.     [HttpGet]    
  9.     public JsonResult EmpDetails()    
  10.     {    
  11.     //Creating List    
  12.         List<Employee> ObjEmp = new List<Employee>()    
  13.         {    
  14.     //Adding records to list    
  15.     new Employee {Id=1,Name="Vithal Wadje",City="Latur",Address="Kabansangvi" },    
  16.     new Employee {Id=2,Name="Sudhir Wadje",City="Mumbai",Address="Kurla" }    
  17.         };    
  18.     //return list as Json    
  19.     return Json(ObjEmp, JsonRequestBehavior.AllowGet);    
  20.     }    
  21. }  
In the above controller class JsonResult method EmpDetails we have added the records into the Generic list and returning it as JSON to avoid database query for same result.

Possible Error

If you return JSON method without setting JsonRequestBehavior property to AllowGet then the following error will occur.

Why error occurred ?
The GET request by default not allowed in JSON result so to allow GET request in JsonResult we need to set JsonRequestBehavior to AllowGet as in the following code snippet:
  1. Json(ObjEmp, JsonRequestBehavior.AllowGet);  
Now run the application and the Json result output will be shown into the browser as in the following screenshot:

Now we have successfully returned the JsonResult, let's bind view from this JsonResult as in the following step:
Step 4: Add Partial view.

Right click on Home folder inside the View folder in the created MVC application as in the following screenshot:

Give the name EmpDetails and click Add button.
To bind view using json we need JQuery and the following JQuery library to communicate to the controller from view:
  1. <script src="~/Scripts/jquery-1.10.2.min.js"></script> 
 The preceding JQuery library file version may be different (lower or higher). Now write the following code into the partial view created:
  1. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  2. <script>  
  3.     $(document).ready(function () {  
  4.         //Call EmpDetails jsonResult Method  
  5.         $.getJSON("Home/EmpDetails",  
  6.         function (json) {  
  7.         var tr;  
  8.         //Append each row to html table  
  9.         for (var i = 0; i < json.length; i++) {  
  10.                 tr = $('<tr/>');  
  11.                 tr.append("<td>" + json[i].Id + "</td>");  
  12.                 tr.append("<td>" + json[i].Name + "</td>");  
  13.                 tr.append("<td>" + json[i].City + "</td>");  
  14.                 tr.append("<td>" + json[i].Address + "</td>");  
  15.                 $('table').append(tr);  
  16.             }  
  17.         });  
  18.     });  
  19. </script>  
  20. <table class="table table-bordered table-condensed table-hover table-striped">  
  21.         <thead>  
  22.         <tr>  
  23.         <th>Id</th>  
  24.         <th>Name</th>  
  25.         <th>City</th>  
  26.         <th>Address</th>  
  27.         </tr>  
  28.         </thead>  
  29.         <tbody></tbody>  
  30. </table> 
Step 5: Call partial view EmpDetails in Main Index view.

Now call the partial view EmpDetails in Main Index view as in the following code
  1. @{  
  2.     ViewBag.Title = "www.compilemode.com";  
  3. }  
  4. <div style="margin-top:20px">  
  5. @Html.Partial("EmpDetails");  
  6. </div> 
 Step 6 : Run the application.

From the preceding examples we have learned about JsonResult type using the scenario on how to bind view using JSON data in ASP.NET MVC. 

  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
  • Handle the exception in the database or text file as per you convenience, since in this article I have not implemented it.

I hope this article is useful for all the readers. If you have any suggestion please contact me.

Up Next
    Ebook Download
    View all
    View all