Monday, 22 July 2013

Working with PartialViews in MVC4

Hi, Its not been a long time for me to started working with MVC. What I saw is that lot of developers find it difficult to start with Partial views.
For those who are coming from the background of Web Form it is not at all difficult to compare it with Web User Controls. Just like we can display the User Control on any page we want by Registering the control, Same way we can use the Partial View in MVC.

Here in this post i will be following 2 steps, First will be creating Partial Views and Second will be calling that Partial View in View.

Lets start with the First step:

Creating a Partial View

Partial View can be created by following ways:

First: By Right clicking on Views folder in which you want to create the view.

After this step one PopUp will appear for asking you if you want to create the View as Strongly typed.
In that popup one checkbox will be there for Partial View.

Second: By using Add New Item option

Note: Using this Second option you will not get the option for creating the view as partial view.

After this we will get a blank page and we can put any HTML content we want in Partial View.
I am displaying some RAW content.

Calling a Partial View

For calling a partial view you can use two methods.
          1. @Html.Partial(string Viewname)

This returns a string, means you can store the output of this into any variable also Or return it from function.

          2. Html.RenderPartial(string Viewname)
This internally returns Void. Result is written directly to Response stream during the execution.

Using in Razor and Aspx:

Razor Syntax:


Aspx Syntax:

<%: Html.Partial("ViewName") %>

<% Html.RenderPartial("ViewName"); %>

PS: Partial Views can also be created as Strong Views.

No comments:

Post a Comment