Partial View In ASP.NET MVC

Introduction

This article introduces partial view in ASP.NET MVC. When we need a common part of user interface at multiple pages in web application then we develop a partial view, hence partial view is regular view which can be used multiple times in an application and has file extension .cshtml. Sometimes we also use partial view to divide a web page in small parts such as header, footer and menu on Layout. Other examples are comments in blogging site, shipping and billing address in invoice in ecommerce site etc. A partial view is similar user control in web form application.

Using the Code

We create a sample application to understand partial view which showsa person's listing with their multiple addresses so we develop a partial view for address. We create two tables one is Person and another is Address which has one to many relationship as per figure 1.

table
            Figure 1: Person and Address tables

To create partial view, we do right click on folder of views then expand Add option which has ‘MVC 5 Partial Page (Razor)’ as figure 2.

Page
                                       Figure 2: Partial View option

Now we click on partial page option then we get a window where we put the name of partial view as figure 3. Click on ok then partial view created in selected view folder.

View
           Figure 3: Partial View Name Window

Now the following code snippet for _PersonAddress partial view which shows an address.

  1. @model EFOperation.Data.Address  
  2. <address>  
  3. @Model.Address1<br/>  
  4. @Model.Address2<br/>  
  5. @Model.City,@Model.Postcode  
  6. </address>  
  7. <hr/>  
Now we create Index action method under PersonController which retrieve all person details with their addresses and returns on view. The following code snippet for Index action method.
  1. [HttpGet]  
  2. public ActionResult Index()  
  3. {  
  4.     List < Person > people = new List < Person > ();  
  5.     using(OperationEntities context = new OperationEntities())   
  6.     {  
  7.         people = context.People.Include(p => p.Addresses).ToList();  
  8.     }  
  9.     return View("Index", people);  
  10. }  
The Index view renders the person's detail with their addresses and following code snippet for same.
  1. @model List  
  2. <EFOperation.Data.Person>  
  3.     <h4>People List</h4>  
  4.     <hr />  
  5.     <table class="table-condensed table-bordered table-responsive">  
  6.         <thead>  
  7.             <tr>  
  8.                 <th>Name</th>  
  9.                 <th>Email</th>  
  10.                 <th>Address</th>  
  11.             </tr>  
  12.         </thead>  
  13.         <tbody>  
  14. @foreach (var person in Model)  
  15. {  
  16.   
  17.             <tr>  
  18.                 <td>@person.Name</td>  
  19.                 <td>@person.Email</td>  
  20.                 <td>  
  21. @foreach (var address in person.Addresses)  
  22. {  
  23. @Html.Partial("_PersonAddress", address)  
  24. }  
  25.   
  26. </td>  
  27.             </tr>  
  28. }  
  29.   
  30.         </tbody>  
  31.     </table>  
In the above index view we call partial view with help of Html helper method @Html.Partial(). We have two similar options to call a partial view one is @Html.Partial() and another is @Html.RenderPartial(). Apart from these we have other options to call partial view are Html.Action() and Html.RenderAction().

@Html.Partial

This Html.Partial renders partial view as an HTML string so we can store it in another string variable. It is string return type method so first it returns result as a string then renders result to response.

@Html.RenderPartial

This is also same as Html.Partial but main difference is that it renders result directly to response which means it writes response internally that’s why it is more efficient if the view has a large amount of HTML over @Html.Partial.
The output of the above implementation is as figure 4.

output
      Figure 4: Output of partial view

Rendering a Partial View using Ajax

We can also call partial using ajax request, in other words partial view can be called by jQuery at client side. By rendering a partial view using ajax, we create an example in which user chooses person from dropdown list and respective address will be rendered below that.
 

We create a model which is used to pass the person's data from action method to view. The following code snippet for PersonDetailViewModel.
  1. using System.Collections.Generic;  
  2. using System.ComponentModel.DataAnnotations;  
  3. using System.Web.Mvc;  
  4. namespace EFOperation.Models  
  5. {  
  6.     public class PersonDetailViewModel   
  7.     {  
  8.         public PersonDetailViewModel()   
  9.         {  
  10.                 Persons = new List < SelectListItem > ();  
  11.             }  
  12.             [Display(Name = "Person")]  
  13.         public int PersonId   
  14.         {  
  15.             get;  
  16.             set;  
  17.         }  
  18.         public List < SelectListItem > Persons   
  19.         {  
  20.             get;  
  21.             set;  
  22.         }  
  23.     }  
  24. }  
Now we create an action method PersonDetail in same Person controller which populates person data in model and return view. The following code snippet for the same.
  1. [HttpGet]  
  2. public ActionResult PersonDetail()  
  3. {  
  4.     using(OperationEntities context = new OperationEntities())  
  5.     {  
  6.         PersonDetailViewModel model = new PersonDetailViewModel();  
  7.         model.Persons = context.People.ToList().Select(p => new SelectListItem  
  8.         {  
  9.             Text = p.Name,  
  10.                 Value = p.PersonId.ToString()  
  11.         }).ToList();  
  12.         return View(model);  
  13.     }  
  14. }  
After that we define view for above action method that has a dropdown list which populates by person name and id. The below code snippet for same. 
  1. @model EFOperation.Models.PersonDetailViewModel  
  2.   
  3.   
  4. <h2>Person Detail</h2>  
  5. <hr />  
  6. <div class="form-group">  
  7. @Html.LabelFor(m => m.PersonId, new { @class = "col-md-2 control-label" })  
  8.   
  9.     <div class="col-md-10">  
  10. @Html.DropDownListFor(m => m.PersonId, Model.Persons, new {@class="form-control" })  
  11. </div>  
  12. </div>  
  13. <div class="form-group">  
  14.     <div id="addresses"></div>  
  15. </div>  
  16. @section Scripts{  
  17. @Scripts.Render("~/Scripts/person-detail.js")  
  18. }  
As we show person’s addresses on selection so we can create action method that returns the  person's address as per selected person that action method returns partial view.
  1. public PartialViewResult PersonAddressList(int id)  
  2. {  
  3.     using(OperationEntities context = new OperationEntities())   
  4.     {  
  5.         List < Address > addresses = context.Addresses.Where(a => a.PersonId == id).ToList();  
  6.         return PartialView("_PersonAddressList", addresses);  
  7.     }  
  8. }  
After that we create partial view for addresses, so we right click on action method name and choose ‘Add View’ option as per figure 5.

view
                                       Figure 5: Create Partial View

We write following code snippet for this partial view which shows multiple addresses for a person.
  1. @model List<EFOperation.Data.Address>  
  2. @foreach(EFOperation.Data.Address address in Model)  
  3. {  
  4.     <address>  
  5.     @address.Address1<br />  
  6.     @address.Address2<br />  
  7.     @address.City,@address.Postcode  
  8.     </address>  
  9.     <hr />   
  10. }  
To render a partial view i.e render above _PersonAddressList partial view using ajax we create js file in which we call partial view action method using ajax GET request per following code snippet.
  1. (function($)  
  2.  {  
  3.     function PersonDetail()   
  4.   {  
  5.         var $this = this;  
  6.   
  7.         function intialize()   
  8.     {  
  9.             $("#PersonId").change(function()   
  10.              {  
  11.                 var address = $("#addresses");  
  12.                 address.html('');  
  13.                 $.get("PersonAddressList",   
  14.                 {  
  15.                     id: $(this).val()  
  16.                 }, function(data)   
  17.                 {  
  18.                     address.html(data);  
  19.                 })  
  20.             });  
  21.         }  
  22.         $this.init = function()   
  23.         {  
  24.             intialize();  
  25.         }  
  26.     }  
  27.     $(function()   
  28.       {  
  29.         var self = new PersonDetail();  
  30.         self.init();  
  31.     })  
  32. })(jQuery)  
Now run the application and choose person from dropdown list and respective addresses render as per figure 6.

view
                  Figure 6: Partial view render using Ajax

We can also call partial view using load method of jQurey.


Similar Articles