Monday, December 3, 2012

Partial View in MVC

A partial view is a fragment of the code that can be reused in some other view; this will help us in reducing the duplicate code.  We can say a partial view in MVC is some what similar to the normal user controls in the traditional ASP.NET.  There can be 2 different form of these depending upon the engine you are using for the same for example in Razor engine it will be saved as .cshtml and for asp engine it will be a normal user control that is .ascx

The partial view will be very helpful in the websites or pages where there are multiple section present in the same page for example a New site where multiple section for each kind of news are present. We can create all these section in various partial views thus there will be lesser amount of code will be required and it will become easier to manage. Other example of partial views can be the icon which we used for the social book marking.

Partial views are only a subset of the view as the View can produces the entire HTML page but the partial view only create a part of the page, we can not specify the layout of the page using partial view for this we should have to make use of the View.

We can create the partial view by Right Clicking on the View >> Shared Folder and then add a new view and make sure you select the Checkbox for making it as a partial view. It is advisable to create the partial view in the shared folder as it is a good practice.



For calling the partial view we make use of the Helper method. “Renderpartial”, Please check the below sample code.

<div class="clear">
       <%Html.Partial("ViewTest1") %>
</div>


The partial view returns an action method as follows

public class Test
{
  public ActionResult getDetails()
  {
     return PartialView(); 
  }

}



Hope you will like this post and get more idea about the partial view in MVC. Please feel free to provide your valuable comment on this post so that I can improve and can create some more valuable articles, Cheers

Thanks
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC,DNS MVM


Kontera