Rendering a Partial View and JSON Data Using AJAX in ASP.Net MVC

Introduction

This article explains how to render a partial view and JSON data using AJAX. I have divided this article into three sections to understand both concepts, the first section describes the basic code and structure that is common in both concepts, the second section describes how to render a partial view using AJAX and the last section describes how to render JSON data on a web using AJAX.

I will explain these concepts with a simple example. The example is that books are showing in a web depending on publisher.  I choose a publisher from a dropdown list then the books information is shown in the web page depending on publisher. So let’s see this example in detail.
 
Getting Started
 
I add the ADO.NET Entity Model to the application to do the database operations mapped from the “Development” database. The ADO.NET Entity Model is an Object Relational Mapping (ORM) that creates a higher abstract object model over ADO.NET components. This ADO.NET Entity Model is mapped the with “Development” database so context class is “DevelopmentEntities” that inherits the DbContext class.

This “Development” database has two tables, one is the Publisher table and the other is the BOOK table. Both tables have 1-to-many relationships, in other words one publisher can publish multiple books but each book is associated with one publisher. If you want to learn more about this application database design then please check my previous article “An MVC Application with LINQ to SQL”.

The ADO.NET Entity Model is mapped to both tables. The connection string for this has the same name as the context class name and this connection string is created in the web.config file. You can change the name of the connection string. The context class name and connection string name is just a convention, not a configuration, so you can change it with a meaningful name. The following Figure 1.1 shows the ADO.NET Entity Model mapping with both tables.

Entity Model mapping
Figure 1.1 The ADO.NET Entity Model mapping with Publisher and Book tables.
 
Now the ADO.NET Entity Model is ready for the application and it's time to move on the next step of the application that is the model design so let’s see the application’s model.
 
Model Design
 
As you already know, the purpose of the application is to create two entities (Publisher and BOOK) that I have already created as the same therefore I need to create two models, one for the publisher and the other for the books.
 
I create a publisher model (Publisher.cs) under the Model folder that has a publisher id and publisher list as in the following code snippet.

  1. using System.Collections.Generic;  
  2. using System.ComponentModel.DataAnnotations;  
  3. using System.Web.Mvc;  
  4.    
  5. namespace JsonRenderingMvcApplication.Models  
  6. {  
  7.     public class PublisherModel  
  8.     {  
  9.         public PublisherModel()  
  10.         {  
  11.             PublisherList = new List<SelectListItem>();  
  12.         }  
  13.    
  14.         [Display(Name="Publisher")]  
  15.         public int Id { getset; }  
  16.         public IEnumerable<SelectListItem> PublisherList { getset; }  
  17.     }  
  18. }   

After the publisher model, I create a book model (Book.cs) in the same folder. That has basic properties related to a book. The following is a code snippet for the book model.

  1. namespace JsonRenderingMvcApplication.Models  
  2. {  
  3.     public class BookModel  
  4.     {  
  5.         public string Title { getset; }  
  6.         public string Author { getset; }  
  7.         public string Year { getset; }  
  8.         public decimal Price { getset; }  
  9.     }  
  10. }  

Now the models are ready for use so now to move on to the controller.
 
Controller Design  
 
I create two controllers, one for publisher that shows a publisher’s list in a dropdown list and another is a book controller that shows book details depending on publisher. The publisher controller defines a single action method that is the same in both concepts; rendering a partial view and JSON data while the book controller defines two action methods, one for partial view rendering and another for JSON data rendering so you will look it later in this article.
 
Now create a publisher controller (PublisherController.cs) under the Controllers folder as per the MVC convention. This control has a single action method to show the publisher list on the view. The following is a code snippet for the publisher controller.

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.Web.Mvc;  
  4. using JsonRenderingMvcApplication.Models;  
  5.    
  6. namespace JsonRenderingMvcApplication.Controllers  
  7. {  
  8.     public class PublisherController : Controller  
  9.     {  
  10.         public ActionResult Index()  
  11.         {  
  12.             PublisherModel model = new PublisherModel();  
  13.             using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())  
  14.             {  
  15.                 List<DAL.Publisher> PublisherList = context.Publishers.ToList();  
  16.                 model.PublisherList = PublisherList.Select(x =>  
  17.                                         new SelectListItem()  
  18.                                         {  
  19.                                             Text = x.Name,  
  20.                                             Value = x.Id.ToString()  
  21.                                         });  
  22.                                  }  
  23.             return View(model);  
  24.         }  
  25.     }  
  26. }  

Now create book a controller (BookController.cs) under the Controllers folder of the application and leave it empty without any action method, you will define two action methods in this controller, one for partial view rendering and another for JSON data rendering. Now the article’s first section is completed as defined in the introduction and now to move both approaches one by one.
 
Rendering a partial view
 
When making AJAX requests, it is very simple to return HTML content as the result. Simply return an ActionResult using the PartialView method that will return rendered HTML to the calling JavaScript.
 
Now define an action method in the book controller that returns an ActionResult using the PartialView. This action method retrieves a list of books depending on publisher id that passes as a parameter in this action method. The following is a code snippet for this action method.

  1. public ActionResult BookByPublisher(int id)  
  2. {  
  3.     IEnumerable<BookModel> modelList = new List<BookModel>();  
  4.     using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())  
  5.     {  
  6.         var books = context.BOOKs.Where(x => x.PublisherId == id).ToList();  
  7.         modelList = books.Select(x =>  
  8.                    new BookModel()  
  9.                     {  
  10.                              Title = x.Title,  
  11.                              Author = x.Auther,  
  12.                              Year = x.Year,  
  13.                              Price = x.Price  
  14.                    });  
  15.     }  
  16.     return PartialView(modelList);    
  17.  }  

I define a route for this action in the RegisterRoute() method under the RouteConfig class (App_Start/RouteConfig.cs).

  1. routes.MapRoute("BookByPublisher",  
  2.        "book/bookbypublisher/",  
  3.         new { controller = "Book", action = "BookByPublisher" },  
  4.         new[] { "JsonRenderingMvcApplication.Controllers" });  

Now create a view for the publisher that has a dropdown list for the publisher and shows the book details depending on the value selected in the publisher dropdown list using AJAX. This view is an index (Views/Publisher/Index.cshtml). The following is a code snippet for the Index view.

  1. @model JsonRenderingMvcApplication.Models.PublisherModel  
  2. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  3. <script type="text/javascript">   
  4.      
  5.     $(document).ready(function ()  
  6.     {  
  7.         $("#Id").change(function ()  
  8.         {  
  9.              var id = $("#Id").val();  
  10.              var booksDiv = $("#booksDiv");  
  11.              $.ajax({  
  12.                  cache: false,  
  13.                  type: "GET",  
  14.                  url: "@(Url.RouteUrl("BookByPublisher"))",  
  15.                 data: { "id": id },  
  16.                 success: function (data)  
  17.                 {  
  18.                     booksDiv.html('');  
  19.                     booksDiv.html(data);  
  20.                 },  
  21.                 error: function (xhr, ajaxOptions, thrownError)  
  22.                 {  
  23.                     alert('Failed to retrieve books.');                      
  24.                 }  
  25.             });  
  26.         });  
  27.     });        
  28. </script>  
  29. <div>  
  30.     @Html.LabelFor(model=>model.Id)  
  31.     @Html.DropDownListFor(model => model.Id, Model.PublisherList)  
  32. </div>  
  33. <div id="booksDiv">  
  34. </div>  

Run the application and choose an item from the publisher dropdown list. You will then get the result as in Figure 1.2.

publisher dropdown list
Figure 1.2: output result using HTML rendering

Rendering JSON Data

In the previous section you have learned that you can render an HTML on AJAX request but in this section you will learn about rendering only serialized data, not entire HTML.  ASP.NET MVC offers native JSON support in the form of the JsonResult action result, which accepts a model object that it serialized into the JSON format. In order to add AJAX support to your controller actions via JSON, simply use the Controller.Json() method to create a new JsonResult containing the object to be serialized.

Now create an action method BooksByPublisherId() in the book controller that returns JsonResult. This action method retrieves a list of books depending on publisher id that passes as a parameter in this action method. The following is a code snippet for this action method.

  1. public JsonResult BooksByPublisherId(int id)  
  2. {  
  3.       IEnumerable<BookModel> modelList = new List<BookModel>();  
  4.       using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())  
  5.       {  
  6.             var books = context.BOOKs.Where(x => x.PublisherId == id).ToList();  
  7.             modelList = books.Select(x =>  
  8.                         new BookModel()  
  9.                         {  
  10.                                    Title = x.Title,  
  11.                                    Author = x.Auther,  
  12.                                    Year = x.Year,  
  13.                                     Price = x.Price  
  14.                            });  
  15.             }  
  16.             return Json(modelList,JsonRequestBehavior.AllowGet);  
  17.         }   

The action method was created to return book details. Here the Controller.Json() method has two parameters, the first one is for the data source that will be serialized and the second parameter is JsonRequestBehavior.AllowGet, which explicitly informs the ASP.NET MVC Framework that it’s acceptable to return JSON data in a response to an HTTP GET request.

The JsonRequestBehavior.AllowGet parameter is necessary in this case because, by default, ASP.NET MVC disallows returning JSON in response to an HTTP GET request in order to avoid potentially dangerous security vulnerability known as JSON hijacking.
This action method returns JSON data as shown in Figure 1.3.

Rendering JSON Data
Figure 1.3 JSON Data from action method

I define a route for this action in the RegisterRoute() method under the RouteConfig class (App_Start/RouteConfig.cs).

  1. routes.MapRoute("BooksByPublisherId",  
  2.       "book/booksbypublisherid/",  
  3.        new { controller = "Book", action = "BooksByPublisherId" },  
  4.        new[] { "JsonRenderingMvcApplication.Controllers" });  

Now modify the previously created Index view for the publisher that has a dropdown list for the publisher and that shows the book details depending on selecting a value in the publisher dropdown list using AJAX. . The following is a code snippet for the Index view.

  1. @model JsonRenderingMvcApplication.Models.PublisherModel  
  2.    
  3. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  4. <script type="text/javascript">  
  5.     $(document).ready(function () {  
  6.         $("#Id").change(function () {  
  7.             var id = $("#Id").val();  
  8.             var booksDiv = $("#booksDiv");  
  9.             $.ajax({  
  10.                 cache: false,  
  11.                 type: "GET",  
  12.                 url: "@(Url.RouteUrl("BooksByPublisherId"))",  
  13.                 data: { "id": id },  
  14.                 success: function (data) {  
  15.                     var result = "";  
  16.                     booksDiv.html('');  
  17.                     $.each(data, function (id, book) {  
  18.                         result += '<b>Title : </b>' + book.Title + '<br/>' +  
  19.                                     '<b> Author :</b>' + book.Author + '<br/>' +  
  20.                                      '<b> Year :</b>' + book.Year + '<br/>' +  
  21.                                       '<b> Price :</b>' + book.Price + '<hr/>';  
  22.                     });  
  23.                     booksDiv.html(result);  
  24.                 },  
  25.                 error: function (xhr, ajaxOptions, thrownError) {  
  26.                     alert('Failed to retrieve books.');  
  27.                 }  
  28.             });  
  29.         });  
  30.     });  
  31. </script>  
  32. <div>  
  33.     @Html.LabelFor(model=>model.Id)  
  34.     @Html.DropDownListFor(model => model.Id, Model.PublisherList)  
  35. </div>  
  36. <div id="booksDiv">  
  37. </div>  

Run the application and choose an item from the publisher dropdown list; you will then get the result as in Figure 1.3.

/Publisher DropDown list using AJAX
Figure 1.4: output result using JSON data rendering

Conclusion

Which one is fast? You can say that JSON data rendering is faster compared to partial view rendering. I make the same request using both approaches and get response data in bytes as shown in the following table.

Content Type Header Body Total (Byte)
text/html 434 375 809
application/ json 398 197 595
Table 1.1 Summary of response bytes

It is big difference when working with a small amount server data. When I represent these statistics using a circle graph then these look like:

circle graph 
 


Similar Articles