Partial View In ASP.NET MVC Using Entity Framework

Introduction

A partial view is same as user control in ASP.NET MVC that is used for code reusability. Partial views help us to reduce code duplication. Hence, partial views can be used for views like Header and Footer views. In web form application, we use user control for creating reusable elements. The same way in MVC, we will use a partial view.

Description
 
Here, I have created an MVC application and built some views including normal view and partial view. Here is the step-by-step description of how to implement partial view instead of writing a whole bunch of code of partial view how to access properties of partial view only by mentioning partial view file name in other views. Also in this module, I used Entity Framework to fetch data from the database and will show the result using a partial view.
 
In Which Scenario Using Partial View
 
A partial view is used to display user comments, module category, site bookmarks buttons, a dynamic ticker, calendar, like count status of blogs etc. 
 
Download Source Code
Steps To Be Followed
 
A partial view has extension .cshtml as a regular view. To create a partial view right click on the shared folder (\Views\Shared) in solution explorer and click on "Add New View" option and then give the name for a partial view and also, check the "Create a partial view" option.
 
It is best practice to create partial view in the shared folder and partial view name is preceded by "_". The "_" before view name specifies that it is a reusable component i.e. partial view. A partial view is rendered by using the ViewUserControl class that is inherited from the ASP.NET UserControl class. The Partial, RenderPartial, RenderAction helper methods are used to render partial view in mvc3 razor.
  1. <div> @Html.Partial("_status") </div>   
  2. div> @{Html.RenderPartial("_status");} </div>  
The Partial helper method renders a partial view into a string while RenderPartial method writes directly into the response stream instead of returning a string.
  1. <div> @{Html.RenderAction("_MyView","Profile");} </div> 
Partial or RenderPartial methods are used when a model for the page is already populated with all the information. RenderAction method is used when some information is needed to show on multiple pages. Hence partial view should have its own model.Sometimes we need to load a partial view with in a popup on run time like as login box, then we can use jQuery to make an AJAX request and render a Partial View into the popup. In order to load a partial view with in a div we need to do like as,
  1. <script type="text/jscript">   
  2.  $('#satyapopup').load('/shared/_MyView’);   
  3. </script>  

Note 

In online news to show Twitter comments we would like to use Partial or RenderPartial methods since aTwitter section information is already populated in the model.To category list of menus on each and every page we would like to use RenderAction method since the list of category is populated by different model. 
 
Different ways for calling a partial view in MVC,
 
Html.RenderPartial Html.RenderAction Html.Partial Html.Action
This method returns void. We need to create a child action for  rendering the partial view. Renders the partial view as an HTML-encoded string. Renders the partial view as an HtmlString .
The method result will be directly written to the HTTP response stream which means it used the same TextWriter object as used in the current webpage/template.
No need to create any action.
This method result will be directly written to the HTTP response stream which means it used the same TextWriter object as used in the current webpage/template. RenderAction method is useful when the displaying data in the partial view is independent from corresponding view model. Result can be stored in a variable, since it returns string type value. Simple to use and no need to create any action.  We need to create a child action for rendering the partial view. This method result can be stored in a variable, since it returns string type value.
This method is faster than Partial method since its result is directly written to the response stream. RenderPartial method is useful when the displaying data in the partial view is already in the corresponding view model. This method is the best choice when you want to cache a partial view. This method is faster than Action method since its result is directly written to the HTTP response stream which makes it fast. Like RenderPartial method, Partial method is also useful when the displaying data in the partial view is already in the corresponding view model. Action method is useful when the displaying data in the partial view is independent from corresponding view model.
 
Build A Sample MVC Application Using Partial View
 
Step-1
 
Added a Entity Data Model named Satyaprakash.edmx and check the created table structure . I inserted some dummy data.
 

Step-2
 
In HomeController.cs file add the below code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MVCPartialView.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         public ActionResult ViewWithPartial()  
  12.         {  
  13.             return View();  
  14.         }  
  15.   
  16.         public ActionResult SatyaAcademicYear()  
  17.         {  
  18.             using (SatyaprakashEntities dc = new SatyaprakashEntities())  
  19.             {  
  20.                 var v = dc.AcademicYears.OrderByDescending(a => a.AcademicYear1).ToList();  
  21.                 return PartialView("_AcademicYear", v);  
  22.             }  
  23.         }  
  24.         public ActionResult ViewWithPartialtwo()  
  25.         {  
  26.             return View();  
  27.         }  
  28.     }  

Here  I created three controller action methods using Actionresult. In SatyaAcademicYear() action method add entity name  and using this class object we access the table properties and in partialview method add the partial view name .
  1. return PartialView("_AcademicYear", v); 
Step-3
 
Create a Partial View named _AcademicYear.cshtml.
  1. @model IEnumerable<MVCPartialView.AcademicYear>  
  2.   
  3. @{  
  4.     ViewBag.Title = "_AcademicYear";  
  5. }  
  6.   
  7. <h2>Academic Year List</h2>  
  8.   
  9. <style>  
  10.     table {  
  11.         font-family: arial, sans-serif;  
  12.         border-collapse: collapse;  
  13.         width: 100%;  
  14.     }  
  15.   
  16.     td, th {  
  17.         border: 1px solid #dddddd;  
  18.         text-align: left;  
  19.         padding: 8px;  
  20.     }  
  21.   
  22.     tr:nth-child(even) {  
  23.         background-color: #dddddd;  
  24.     }  
  25. </style>  
  26.   
  27. <table border="1" cellpadding="4" cellspacing="4">  
  28.     <tr>  
  29.         <th style="background-color: Yellow;color: blue">  
  30.             AcademicYearID  
  31.         </th>  
  32.         <th style="background-color: Yellow;color: blue">  
  33.             AcademicYearName  
  34.         </th>  
  35.     </tr>  
  36.   
  37. @foreach (var item in Model) {  
  38.     <tr>  
  39.         <td>  
  40.             @Html.DisplayFor(modelItem => item.AcademicYear1)  
  41.         </td>  
  42.         <td>  
  43.             @Html.DisplayFor(modelItem => item.AcademicYearID)  
  44.         </td>  
  45.     </tr>  
  46. }  
  47. </table> 
Here i added table column names and show records using foreach loop using AcademicYear entity class.
  1. @foreach (var item in Model) {  
  2.     <tr>  
  3.         <td>  
  4.             @Html.DisplayFor(modelItem => item.AcademicYear1)  
  5.         </td>  
  6.         <td>  
  7.             @Html.DisplayFor(modelItem => item.AcademicYearID)  
  8.         </td>  
  9.     </tr>  

Step-4
 
 Add a View named ViewWithPartial.cshtml.
  1. @{  
  2.     ViewBag.Title = "ViewWithPartial";  
  3. }  
  4.   
  5. <fieldset>  
  6.     <legend style="font-family:Arial Black;color:blue">Normal View Content and Partial View Content</legend>  
  7.     <table>  
  8.         <tr>  
  9.             <td>  
  10.                 <b>Normal View Content One</b>  
  11.                 <p>  
  12.                     <a href="http://www.c-sharpcorner.com/members/satyaprakash-samantaray">  
  13.                         <img src="http://www.c-sharpcorner.com/members/satyaprakash-samantaray/flair.png" width="260" height="58" alt="profile for Satyaprakash C# Corner - A Social Community of Developers and Programmers" title="profile for Satyaprakash at C# Corner - A Social Community of Developers and Programmers" />  
  14.                     </a>  
  15.                     <br />  
  16.                     <br />  
  17.                     I'm a C# Corner MVP , Software Developer, Designer.  
  18.                     I enjoy developing Microsoft .NET technology stuffs.  
  19.                     I am passionate about Microsoft .NET technology and like to contribute my skills to the .NET developers community.  
  20.                     My Contribution will let me step towards to be a future entrepreneur.  
  21.                 </p>  
  22.             </td>  
  23.             <td width="400px">  
  24.                 <b>Partial View Content</b>  
  25.                 @{Html.RenderAction("SatyaAcademicYear""Home");}  
  26.             </td>  
  27.         </tr>  
  28.     </table>  
  29.     </fieldset>  
  30. <footer>  
  31.     <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  32. </footer>   
In this first view I added Normal View Content and accessed Partial View content of partial view file.
  1. <td width="400px">  
  2.                 <b>Partial View Content</b>  
  3.                 @{Html.RenderAction("SatyaAcademicYear""Home");}  
  4.             </td> 
Step-5
 
Add a View named ViewWithPartialtwo.cshtml.
  1. @{  
  2.     ViewBag.Title = "ViewWithPartialTwo";  
  3. }  
  4.   
  5. <fieldset>  
  6.     <legend style="font-family:Arial Black;color:blue">Normal View Content and Partial View Content</legend>  
  7.     <table>  
  8.         <tr>  
  9.             <td>  
  10.                 <b>Normal View Content Two</b>  
  11.                 <p>  
  12.                     <a href="http://www.c-sharpcorner.com/members/satyaprakash-samantaray">  
  13.                         <img src="http://www.c-sharpcorner.com/members/satyaprakash-samantaray/flair.png?theme=dark" width="260" height="58" alt="profile for Satyaprakash C# Corner - A Social Community of Developers and Programmers" title="profile for Satyaprakash at C# Corner - A Social Community of Developers and Programmers" />  
  14.                    </a>  
  15.                     <br />  
  16.                     <br />  
  17.                     I'm a C# Corner MVP , Software Developer, Designer.   
  18.                     I enjoy developing Microsoft .NET technology stuffs.   
  19.                     I am passionate about Microsoft .NET technology and like to contribute my skills to the .NET developers community.   
  20.                     My Contribution will let me step towards to be a future entrepreneur.  
  21.                 </p>  
  22.             </td>  
  23.             <td width="400px">  
  24.                 <b>Partial View Content</b>  
  25.                 @{Html.RenderAction("SatyaAcademicYear""Home");}  
  26.             </td>  
  27.         </tr>  
  28.     </table>  
  29. </fieldset>  
  30. <footer>  
  31.     <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  32. </footer> 
In this second view I added Normal View Content and accessed Partial View content of partial view file. 
 
Step-6
 
In RouteConfig.cs file I set the start page .
  1. routes.MapRoute(  
  2.                name: "Default",  
  3.                url: "{controller}/{action}/{id}",  
  4.                defaults: new { controller = "Home", action = "ViewWithPartial", id = UrlParameter.Optional }  
On page load first time the ViewWithPartial.cshtml show the UI result to the end-user.
 
OUTPUT
 
For First View:
 
http://localhost:50167/Home/ViewWithPartial
 
 
 
For Second View
 
http://localhost:50167/Home/ViewWithPartialtwo 
 
 
 
Gif Image For Better Understanding,
 
 
 
SUMMARY
  • What is partial view in MVC.
  • Implement partial view in multiple pages in MVC.
  • Avoid Duplication of code using Partial View.
  • Partial View using Entity Framework.