Partial Views in MVC

Partial views in MVC

When we need a common part of the user interface at multiple pages in a web application then we develop a partial view, hence partial view is a regular view which can be used multiple times in an application and has the file extension .cshtml. In this article, we will discuss Partial views in MVC. 

Sometimes we also use a partial view to divide a web page into small parts such as header, footer, and menu on Layout. Other examples are comments in blogging site, shipping and billing address in the invoice in e-commerce site etc. 

If you are coming from asp.net web-forms background, then you can realize that partial views in MVC are similar to user controls in asp.net web forms. 

That means a partial view is like as user control in Asp.Net Web forms that are used for code re-usability. Partial views help us to reduce code duplication. Hence partial views are reusable views like as Header and Footer views.

What are Partial Views?

The partial view in MVC is a view that’s rendered within another view. The HTML output generated by executing the partial view is rendered into the calling (or parent) view. Like views, partial views use the .cshtml file extension.

When Should I Use Partial Views?

Partial views are an effective way of breaking up large views into smaller components. They can reduce duplication of view content and allow view elements to be reused. Common layout elements should be specified in _Layout.cshtml. Non-layout reusable content can be encapsulated into partial views.

If you have a complex page made up of several logical pieces, it can be helpful to work with each piece as its own partial view. Each piece of the page can be viewed in isolation from the rest of the page, and the view for the page itself becomes much simpler since it only contains the overall page structure and calls to render the partial views.

We can use the partial view to display blog comments, product category, social bookmarks buttons, a dynamic ticker, calendar etc. 

How can we Call/Display Partial View?

We can call or display partial view within a view mainly in five ways. Those are

  1. Html.RenderPartial
  2. Html.Partial
  3. Html.RenderAction
  4. Html.Action
  5. jQuery load function
Let’s consider this with an example.

It’s common sense for Web Applications to make use of same code over and over again to display/render information and details for their domain objects. For example, an e-shop Web Application would probably render each product in the same way in all web pages.

Consider the following product class.

public class Product
{
    public long ProductID { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
}

The respective View for rendering a List of products in ASP.NET MVC View would be

@foreach (var product in Model)
{
    <div>
        ID: <span>@product.ProductID</span>
        Name: <span>@product.Name</span>
        Category: <span>@product.Category</span>
        Description: <span>@product.Description</span>
        Price: <span>@product.Price</span>
    </div>
}

But this is a just a simple Product class for demonstration purposes. What if we wanted to display objects with twenty or even more properties? And what if we needed to display over and over again this kind of information in many pages in our application? Writing the same code would be quite frustrating and this is where Partial Views Comes into the picture.

Let’s create an MVC Application and show the power of Partial Views.

Create a new ASP.NET Web Application named “PartialViewInMVC” and click on OK as shown below.

Partial views in MVC

In the next screen choose the Empty template and check the MVC checkbox, then click on OK button as shown below.

Partial views in MVC

Add a new Product class in the Models folder as shown below.

namespace PartialViewInMVC.Models
{
    public class Product
    {
        public long ProductID { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
    }
}

Add a new Controller named “ProductController” in the Controllers folder, choosing the Empty MVC5 Controller template and click on ADD button as shown below

Partial Views in MVC

In the next screen provide the controller name as ProductController and click on Add button as shown below

Partial Views in MVC

Copy and Paste the following code in Product Controller as shown below.
public class ProductController : Controller
{
    public ActionResult Index()
    {
        List<Product> products = new List<Product>()
            {
                new Product { ProductID =1, Name ="Product 1", Category = "Category 1", Description ="Description 1", Price = 10m},
                new Product { ProductID =2, Name ="Product 2", Category = "Category 1", Description ="Description 2", Price = 20m},
                new Product { ProductID =3, Name ="Product 3", Category = "Category 1", Description ="Description 3", Price = 30m},
                new Product { ProductID =4, Name ="Product 4", Category = "Category 2", Description ="Description 4", Price = 40m},
                new Product { ProductID =5, Name ="Product 5", Category = "Category 2", Description ="Description 5", Price = 50m},
                new Product { ProductID =6, Name ="Product 6", Category = "Category 2", Description ="Description 6", Price = 50m}
            };
        return View(products);
    }
}

Right-click inside the Index action and select “Add view”. And provide the following details and click on add button as shown below

Partial Views in MVC

Copy and paste the following code in the generated index view

@model IEnumerable<PartialViewInMVC.Models.Product>

@{
    ViewBag.Title = "Index";
}

<h2>Product List</h2>


<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.ProductID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Category)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
       
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ProductID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Category)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        
    </tr>
}
</table>

Change the default controller when Application starts in the RouteConfig.cs file, from “Home” to “Product” as shown below.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Product", action = "Index", id = UrlParameter.Optional }
        );
    }
}
Build and run your application. The result should look as shown below

Partial Views in MVC

When we need to use both the same fragments of Razor tags and HTML markup in several different places, we create and use them as Partial Views.

Let’s see how this works. Right-click the /Views/Shared folder and

1. select Add -> View

and then provide the following details

View Name = ProductDetails

Template = List

Model Class = Product (PartialViewInMVC.Models)

Check the Create a partial View check box and click on Add button as shown below

Partial Views in MVC

Copy and paste the following details in the generated ProductDetails partial view as shown below

@model IEnumerable<PartialViewInMVC.Models.Product>
<div class="container">
    <div class="col-md-6">
        <h2>Product List</h2>
        <table class="table">
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.ProductID)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Category)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Description)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Price)
                </th>
            </tr>

            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductID)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Category)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Description)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Price)
                    </td>

                </tr>
            }
        </table>
    </div>
</div>

To use this Partial view, remove the respective code in the Index View and replace it with Html.Partial helper method as shown below.

@model IEnumerable<PartialViewInMVC.Models.Product>
@{
    ViewBag.Title = "Index";
}
@Html.Partial("ProductDetails", Model)

Build and run your application and see that everything is working as expected. But this time you can re-use this partial view wherever you want and moreover if you decide to change how product objects are rendered, the only View you need to change is the ProductDetails partial view. The above @Html.Partial helper method passed a List<Product> object in the “ProductDetails” partial view. The partial view was dynamically rendered.

In the next article, I will discuss different ways of calling Partial views in MVC.

SUMMARY
In this article, I try to explain Partial View in MVC application step by step with a real-time example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *