Partial View in MVC Razor

In general, a Partial View is like a web user control in ASP.Net applications. Partial Views and User Controls serve the same purpose.

Uses of Partial Views

  • A partial view can be used as a reusable component that can be called or used from multiple and different views.

  • A partial view contains reusable mark-up if you want to render from inside multiple views.

  • The partial view are used to render a consistent look like header, footer, comments and so on.

Rendering Partial View: We can render a partial view using one of the following 4:

  1. Html.Partial
  2. Html.RenderPartial
  3. Html.Action
  4. Html.RenderAction

Now in my example, I will add a partial view. For this go to Solution Explorer then select Views -> Shared Folder -> Right-click -> Add View.

Add View
Image 1

Give a name to your View and check Create As a partial View as in the following:

create as a partial view
Image 2

Now I am writing a line of text in this Partial View:

Partial View
Image 3

Now for the Home controller, here I add a new action ShowMyPartialView(). So after it my Home Controller will look such as below:

home controller
Image 4

Now for the View -> Home -> Index.cshtml.

Here I am rendering a Partial View using 4 types, so the index.cshtml will be like the following:

  1. @{  
  2.     ViewBag.Title = "Home Page";  
  3. }  
  4. @section featured {  
  5.     <section class="featured">  
  6.         <div class="content-wrapper">  
  7.             <hgroup class="title">  
  8.                 <h1>@ViewBag.Title.</h1>  
  9.                 <h2>@ViewBag.Message</h2>  
  10.             </hgroup>  
  11.   
  12.         </div>  
  13.     </section>  
  14. }  
  15. <h3>Rendering Partial View:</h3>  
  16. <ol class="round">  
  17.     <li class="one">  
  18.         <h5>By Using Html.RenderPartial #</h5>  
  19.         @{Html.RenderPartial("MyPartial"); }  
  20.     </li>  
  21.   
  22.     <li class="two">  
  23.         <h5>By Using Html.Partial #</h5>  
  24.         @Html.Partial("MyPartial")  
  25.     </li>  
  26.   
  27.     <li class="three">  
  28.         <h5>By Using Html.RenderAction #</h5>  
  29.         @{Html.RenderAction("ShowMyPartialView""Home");}  
  30.     </li>  
  31.     <li class="four">  
  32.         <h5>By Using Html.Action #</h5>  
  33.         @Html.Action("ShowMyPartialView");}  
  34.     </li>  
  35. </ol  
Now run the application:

Partial View demo
Image 5


Similar Articles