Partial Page implementations in ASP.NET MVC3 Razor

Partial page is use for create reusable components filled with content & code.

In Web Forms, we could do this by creating a web user control or a web server control, but in MVC, we will use partial views.

The code below demonstrates the call for partial view.

<div>
  @Html.Partial(
"_List")
</div>

The naming convention of the partial page name should begin at "_".

Now I am going to showing how to implement this.

In modern mvc3 scenario we have "create" and "edit" scenario.

So normally we have "create.cshtml" and "edit.cshtml".

All the razor view code are same but in controller class the action results are different.

So now in that case we will create a partial page name "_CreateOrEdit.cshtml". In this page.

We will write code our actual functionality.

So first create a partial page by right click your view folder and give the name of that file and do like the below image step.

mvc.gif

Here My "_CreateOrEdit.cshtml" will create with code generation.

You can also manually copy the code from "create.cshtml" and paste it into "_CreateOrEdit.cshtml" file.

Now go to your "crete.cshtml" and "edit.cshtml" razore file and replace with the below code:

@model ContactGroups.Models.Contact 
@{
    ViewBag.Title = "Create";
} 
<h2>Create</h2> 
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 
@using (Html.BeginForm()) {
    @* @Html.AntiForgeryToken()
*@
    @Html.ValidationSummary(true)
    <fieldset
> 
        
@Html.Partial("_CreateOrEdit",Model);
    </fieldset>
}

See here I have used "@Html.Partial" properties to call my partial page.

That's it. You don't have to change any code in controller class.

Here In this example I have used partial page for create and edit functionality.

You can can use in your own requirements. Main thing is that it should be reusable.

Conclusion

SO in this article we have get to know what is the purpose of using partial page in mvc3 razor and how to use this. Thankx..