Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Partial View in ASP.NET MVC 4

0.00/5 (No votes)
8 Jul 2013 1  
This article will help you to create partial views in asp.net mvc 4 with razor.

Introduction

If you want to reuse a view in your web application, you can go for the partial view concept. Partial view is like a regular view with a file extension .cshtml. We can use partial views in a situation where we need a header, footer reused for an MVC web application. We can say that it’s like a user control concept in ASP.NET.

Using the code

Here I am going to explain how to create a partial view in an MVC 4 ASP.NET application.

First add a view to the shared folder with the view name _Product. The best way to create a partial view is with the name preceded by '_', because the name specifying that it is reusable.

Here in this example, I am using the partial view to display the item selected in the webgrid. Creating the webgrid example is in the below link:

Add HTML controls in the partial view to display the selected item:

@model PartialViewSample.Models.Product

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AddProduct</title>    
</head>
<body>
    <div>      
           <label>Id:</label>
            @Html.TextBox("Id", Model.Id)
             <label>Name:</label>
            @Html.TextBox("Name", Model.Id)
             <label>Description:</label>
            @Html.TextBox("Description", Model.Description)
             <label>Quantity:</label>
            @Html.TextBox("Quantity", Model.Quantity)
    </div>
</body>
</html>

We can call the partial view in a normal view like:

Html.RenderPartial("~/Views/Shared/_Product.cshtml", product);

Or

@Html.Partial("~/Views/Shared/_Product.cshtml", product);

Html.Partial returns a string, Html.RenderPartial calls Write internally, and returns void. You can store the output of Html.Partial in a variable, or return it from a function. You cannot do this with Html.RenderPartial because the result will be written to the Response stream during execution. So @html.RenderPartial() has faster execution than @html.Partial() due to RenderPartial giving quick response to the output.

We can call the partial view if the grid has a selected item. The code block is shown here:

@if (grid.HasSelection)
{
    product =(PartialViewSample.Models.Product)grid.Rows[grid.SelectedIndex].Value;        
    Html.RenderPartial("~/Views/Shared/_Product.cshtml", product);           
}

History

  • 4th July, 2013: Initial post. 

This tip is based on this blog.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here