Sending PartialView Through jQuery Ajax Request In ASP.NET MVC

Introduction
 
Generally we use PartialView when we implement shared component in ASP.NET MVC. For instance, there is a requirement to display top members in couple of pages, in this scenario we need to create a PartialView and use in which page it is required. It helps to create reusable component to reduce code duplicity. PartialView behaves like UserControl in ASP.NET web forms. Examples of using PartialView: 
  1. Header/Footer in each page in application.
  2. A calendar widget multiple pages in application.
  3. A social networking component used on multiple pages, such as a Facebook Like button. 
Suppose you need to load partially a webpage on demand and that needs to implement only couple of pages. Then how we will achieve this in MVC? So this article helps you to implement the same through sending PartialView using jQuery AJAX concept. Here I am taking an example as to display top members with ID, FirstName, LastName in view.
 
Here are the steps to implement the same:
 
Step 1

Add an entity class(Employee.cs) which is Employee Type in Models folder. Here we will define all the properties which are needed in our PartialView. Here's the code: 
  1. public class Employee  
  2. {  
  3.     public int EmpID { getset; }  
  4.     public string FirstName { getset; }  
  5.     public string LastName { getset; }  
  6. }  
Step 2

Add a user control (DemoPartial.cshtml) in Views/Shared folder. In the following code we are looping over Model and creating HTML table rows to display members.
  1. @model IEnumerable<MvcApplication.Models.Employee>  
  2.   
  3. <table cellpadding="1" cellspacing="1" border="1">  
  4.     <tr>  
  5.         <th>ID</th>  
  6.         <th>Firstname</th>  
  7.         <th>LastName</th>  
  8.     </tr>  
  9.     @foreach (var item in Model)  
  10.     {  
  11.         <tr>  
  12.             <td>@item.EmpID</td>  
  13.             <td>@item.FirstName</td>  
  14.             <td>@item.LastName</td>  
  15.         </tr>  
  16.     }  
  17. </table>  
Step 3

Add action (GetResultByAjax) in Controller (Home) for AJAX request. Here we will create an Employee list and return PartialView(DemoPartial) with Employee list as Model. I added demo employees in code, you can implement your own logic to fetch employees from the database or any other data source. Here's the code:
 
  1. [HttpPost]  
  2. public ActionResult GetResultByAjax()  
  3. {  
  4.      List<Employee> empList = new List<Employee>()  
  5.      {  
  6.          new Employee{EmpID = 1, FirstName = "Mahesh", LastName = "Chand"},  
  7.          new Employee{EmpID = 2, FirstName = "Parveen", LastName = "Kumar"},  
  8.          new Employee{EmpID = 3, FirstName = "Dinesh", LastName = "Beniwal"},  
  9.          new Employee{EmpID = 4, FirstName = "Dhananjay", LastName = "Kumar"}  
  10.      };  
  11.   
  12.      return PartialView("DemoPartial", empList);  
  13. }  
Step 4

Add a View page(Index.cshtml) and add the following code.
 
Add an HTML div tag where PartialView result will bind and display.
  1. <div id="empList">  
  2. </div>  
Then add the following javascript code to send AJAX request. Here we will call the action (defined in Step3) and it will return partial view result. Then we will bind it to DOM element.
 
Also add jQuery reference to send AJAX request and bind result to DIV.
  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  2. <script type="text/javascript">  
  3.    $(document).ready(function () {  
  4.        $.ajax({  
  5.            url: '/Home/GetResultByAjax',  
  6.            datatype: "json",  
  7.            type: "post",  
  8.            contenttype: 'application/json; charset=utf-8',  
  9.            async: true,  
  10.            success: function (data) {  
  11.                $("#empList").html(data);  
  12.            },  
  13.            error: function (xhr) {  
  14.                alert('error');  
  15.            }  
  16.        });  
  17.    });   
  18. </script>  
See the following figure 1, we are getting HTML content response from server as result:
  
Figure 1: Response of AJAX request
 
Output:
 
See the following figure 2, how it is displaying employee in View.
 
 
Figure 2: Output of PartialView result 
 
Conclusion
 
In this article we discussed how to send partial view through AJAX request in ASP.NET MVC. It will help you when you want to load a page partially on demand or want to create a reusable component in MVC.
 
Happy Coding!!


Similar Articles