Partial View in Asp.net MVC3 Razor


A partial view is like as user control in Asp.Net Web forms that is used for code re-usability. Partial views helps us to reduce code duplication. Hence partial views are reusable views like as Header and Footer views.
We can use partial view to display blog comments, product category, social bookmarks buttons, a dynamic ticker, calendar etc. For understanding the different rendering ways of partial view refer the article RenderPartial vs RenderAction vs Partial vs Action in MVC Razor

Creating A Partial View

A partial view has same file extension(.cshtml) as regular view. To create a partial view do right click on shared folder (\Views\Shared) in solution explorer and click on "Add New View" option and then give the name for partial view and also checked the Create a partial view option as shown in fig.
 

Note

  1. It is best practice to create partial view in the shared folder and partial view name is preceded by "_", but it is not mandatory. The "_" before view name specify that it is a reusable component i.e. partial view.

Rendering Partial View

A partial view is rendered by using the ViewUserControl class that is inherited/derived 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("_Comments") </div>
  2. <div> @{Html.RenderPartial("_Comments");} </div>
The main difference between above two methods is that 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("_Category","Home");} </div>

Note

  1. Partial or RenderPartial methods are used when a model for the page is already populated with all the information. For example in a blog to show an article comment we would like to use Partial or RenderPartial methods since an article information are already populated in the model.
  2. RenderAction method is used when some information is need to show on multiple pages. Hence partial view should have its own model. For example to category list of articles on each and every page we would like to use RenderAction method since the list of category is populated by different model.

Render Partial View Using jQuery

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. $('#divpopup').load('/shared/_ProductCategory’);
  3. </script>

Do you want more TechChaitu Updates ?
Enter your email address:

Comments

Popular posts from this blog