Partial Views in ASP.NET MVC

Partial Views in ASP.NET MVC Application

In this article, I am going to discuss Partial Views in ASP.NET MVC Application. Please read our previous section articles where we discussed Action Results in ASP.NET MVC Application. At the end of this article, you will understand what are Partial Views in MVC and Why do we need partial Views, and how to implement Partial Views in the ASP.NET MVC Application with Examples.

Why do we need Partial Views in the ASP.NET MVC Application? or When Should I Use Partial Views?

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 that can be used multiple times in an application and has the file extension .cshtml.

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 on blogging site, shipping and billing address in the invoice in e-commerce site, etc. 

If you are coming from an ASP.NET WebForms background, then you can compare the Partial views in the ASP.NET MVC Application with user controls in the ASP.NET WebForms application. That means a Partial View is like user control in Asp.Net Webforms that are used for code re-usability. Partial views help us to reduce code duplication. Hence partial views are reusable views like Header and Footer views.

What are Partial Views in MVC Application?

The Partial Views in ASP.NET MVC Application are the views that are rendered within another view. The HTML output generated by partial view is rendered into the calling (or parent) view. Like views, partial views use the .cshtml file extension.

How can we Call/Display Partial View?

We can call or display partial view within a view mainly in five ways. They are as follows:

  1. Html.RenderPartial
  2. Html.Partial
  3. Html.RenderAction
  4. Html.Action
  5. jQuery load function
Example: Partial Views in ASP.NET MVC Application.

Let us understand Partial Views in ASP.NET MVC Application with an example. It is a common task in Web Applications to make use of the 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 on 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 View for rendering the list of products in ASP.NET MVC View would be something like below

@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>
}

This is 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 this information on many pages in our application? Writing the same code, again and again, would be time-consuming, error-prone, and maintenance becomes a headache as if we want to do any modification, then we need to do it at all the places. This is where Partial Views Comes into the picture in ASP.NET MVC Application.

Create an ASP.NET MVC Application and understand the power of Partial Views.

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

Creating ASP.NET MVC 5 Application

Once you click on the OK, it will open the “New ASP.NET Web Application” window to select the Project Template. In this window choose the Empty template and check the MVC checkbox, then click on the OK button as shown in the below image.

Partial Views in ASP.NET MVC Application

Once you click on the OK button, it will create an empty ASP.NET MVC 5 Project.

Creating Model:

Add a new class file with the name Product.cs within the Models folder and then copy and paste the following code into it.

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; }
    }
}
Creating Controller:

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

ASP.NET MVC Partial Views with Examples

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

MVC Partial Views Examples

Once the ProductController is created, then copy and paste the following code into it.

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);
    }
}
Creating View:

Right-click inside the Index action method and then select the “Add view” option from the context menu and provide the following details and click on Add button as shown in the below image.

Adding Views in ASP.NET MVC Application

Once the Index View is created, then copy and paste the following code into it.

@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 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 }
        );
    }
}

Now, build and run your application and navigates to Product/Index and you should get the following output.

Partial Views in MVC

When we need a section of a web page (both the Razor tags and HTML markup) in several different places, we create and use them as Partial Views.

How Partial Views are Created in ASP.NET MVC Application?

Right-click on the /Views/Shared folder and Select Add -> View option from the context menu and then provide the following details

  1. View Name = ProductDetails
  2. Template = List
  3. Model Class = Product (PartialViewInMVC.Models)
  4. Check the Create a partial View check box and click on Add button as shown in the below image

How Partial Views are Created in ASP.NET MVC Application

Once the ProductDetails Partial View is created, then copy and paste the following code into it.

@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>
How to use the Partial Views in ASP.NET MVC Application?

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

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

Now, 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 am going to discuss Different ways to Partial Views in ASP.NET MVC Application. Here, in this article, I try to explain Partial Views in ASP.NET MVC application with an example. I hope this Partial Views in MVC article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this Partial Views in the MVC article.

Leave a Reply

Your email address will not be published.