JsonResult Type in 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 ?
It is the type of output format which is shown to the client .
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).
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.
Employee.cs
public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string  Address { get; set; }
    }
Step 3 : Add controller class
Right click on Controller folder in the created MVC application ,give the class name Home or as you 
and click on OK
HomeControlle.cs
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
        return View();
        }
        [HttpGet]
        public JsonResult EmpDetails()
        {
        //Creating List
            List<Employee> ObjEmp = new List<Employee>()
            {
        //Adding records to list
        new Employee {Id=1,Name="Vithal Wadje",City="Latur",Address="Kabansangvi" },
        new Employee {Id=2,Name="Sudhir Wadje",City="Mumbai",Address="Kurla" }
            };
        //return list as Json
        return Json(ObjEmp, JsonRequestBehavior.AllowGet);
        }
    }

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:
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


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:
<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:
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(document).ready(function () {
        //Call EmpDetails jsonResult Method
        $.getJSON("Home/EmpDetails",
        function (json) {
        var tr;
        //Append each row to html table
        for (var i = 0; i < json.length; i++) {
                tr = $('<tr/>');
                tr.append("<td>" + json[i].Id + "</td>");
                tr.append("<td>" + json[i].Name + "</td>");
                tr.append("<td>" + json[i].City + "</td>");
                tr.append("<td>" + json[i].Address + "</td>");
                $('table').append(tr);
            }
        });
    });
</script>
<table class="table table-bordered table-condensed table-hover table-striped">
        <thead>
        <tr>
        <th>Id</th>
        <th>Name</th>
        <th>City</th>
        <th>Address</th>
        </tr>
        </thead>
        <tbody></tbody>
</table>

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

compilemode.com

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.
Watch Video


Note:
  • 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.
Summary
I hope this article is useful for all the readers. If you have any suggestion please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compile Mode