Partial Views in ASP.NET Core MVC

Partial Views in ASP.NET Core MVC

In this article, I will discuss the Partial Views in ASP.NET Core MVC Applications with Examples. Please read our previous article discussing ViewImports in ASP.NET Core MVC Application. At the end of this article, you will understand What Partial Views in ASP.NET Core MVC are, Why We Need Partial Views, and how to implement Partial Views in the ASP.NET Core MVC Application with Examples.

What are Partial Views in ASP.NET Core MVC?

A Partial View is similar to a regular view, but it does not run on its own; instead, it must be invoked from other views or layouts. Like Regular views, Partial Views also use Razor markup to render HTML dynamically. They are typically used to render a portion of HTML content that can be shared by multiple views or to reduce the complexity of a very large view by splitting it into simpler pieces.

That means Partial Views in ASP.NET Core MVC allows us to create reusable components or to break down complex views into simpler, manageable sections. This not only enhances code readability and maintainability but also promotes DRY (Don’t Repeat Yourself) principles in web development. The following are some of the scenarios where you can use Partial Views in ASP.NET Core MVC:

  • Reusable Components: When you have a component (like a banner, a navigation menu, or a footer) reused across multiple pages.
  • Simplifying Complex Views: Breaking down complex views into manageable pieces helps maintain and organize them by separating them into smaller components.
  • Updating Content with AJAX: Partial views can be returned from controller actions for AJAX calls to update a portion of a page without reloading the entire page.
Example to Understand Partial Views in ASP.NET MVC:

It is a common task in Web Applications to use the same code repeatedly to display/render information. For example, an e-commerce Web Application would probably render each product similarly on multiple web pages. Let’s understand how we can implement this using Partial Views in an ASP.NET Core MVC Application. First, let’s create a new ASP.NET Core MVC Web Application named “PartialViewInMVC” using the Model View Controller Project Template.

Creating Product Model:

Create a class file named Product.cs within the Models folder, then copy and paste the following code. This simple class has a few properties to hold the Product information.

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

The View for rendering Product Details in ASP.NET Core MVC View is like the one below.

What are Partial Views in ASP.NET Core MVC?

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 repeatedly would be time-consuming and error-prone, and maintenance becomes a headache; if we need to modify anything, we must do it in all places. This is where Partial Views Come into the picture in the ASP.NET MVC Application.

Creating Product Controller:

Add a new Controller named ProductController within the Controllers folder, and choose the “MVC Controller – Empty” template. Once you Create the ProductController, copy and paste the following code into it.

using Microsoft.AspNetCore.Mvc;
using PartialViewInMVC.Models;

namespace PartialViewInMVC.Controllers
{
    public class ProductController : Controller
    {
        private List<Product> products = new List<Product>();
        public ProductController()
        {
            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}
            };
        }
        
        public ActionResult Details(int Id)
        {
            var ProductDetails = products.FirstOrDefault(prd => prd.ProductID == Id);
            return View(ProductDetails);
        }
    }
}

Next, add the Details.cshtml view within the Views => Product folder. Once you add the view, copy and paste the following code.

@model PartialViewInMVC.Models.Product

@{
    ViewData["Title"] = "Details";
}
<div>
    <h4>Product Details</h4>

    <table class="table">
        <tr>
            <th>
                ProductID
            </th>
            <th>
                Name
            </th>
            <th>
                Category
            </th>
            <th>
                Description
            </th>
            <th>
                Price
            </th>
        </tr>

        <tr>
            <td>
                @Model?.ProductID
            </td>
            <td>
                @Model?.Name
            </td>
            <td>
                @Model?.Category
            </td>
            <td>
                @Model?.Description
            </td>
            <td>
                @Model?.Price
            </td>
        </tr>
    </table>
</div>

Now, run your application and navigate to Product/Details/1, and you should get the following output.

What are Partial Views in ASP.NET Core MVC?

When we need a section of a web page (both the Razor Syntax and HTML Markup) on several different pages, we must create and use them as Partial Views.

How Do We Create a Partial View in ASP.NET Core MVC Application?

Partial views are similar to regular views, but they start with an underscore (_) in their file name to indicate that they are meant to be partial. For example, _ProductDetails.cshtml.

  • Create the Partial View File: In the Views/Shared directory of your ASP.NET Core MVC project, create a new file and name it according to its purpose, for example, _ProductDetails.cshtml. The underscore (_) prefix is a convention to denote partial views but is not mandatory.
  • Define the Model (if needed): At the top of your partial view file, define the model it will use, if any, using the @model directive.
  • Add Markup and Razor Code: Implement the HTML markup and Razor syntax as needed to render the portion of the page the partial view is responsible for.

So, right-click on the /Views/Shared folder, then select the Add -> View option from the context menu. It will open the following window. Here, we need to select Razor View and click the Add button, as shown in the image below.

How to Create a Partial View in ASP.NET Core MVC Application?

Once you click on the Add button, it will open the following window: Here, please provide the View name as _ProductDetails, check the Create as a partial view check box, and then click on the Add button as shown in the image below.

How to Create a Partial View in ASP.NET Core MVC Application?

Once you create the _ProductDetails.cshtml Partial View, open the view file, and copy and paste the following code. Here, you can see we are using Product as the model and then displaying Product information.

@model PartialViewInMVC.Models.Product
<tr>
    <td>
        @Model?.ProductID
    </td>
    <td>
        @Model?.Name
    </td>
    <td>
        @Model?.Category
    </td>
    <td>
        @Model?.Description
    </td>
    <td>
        @Model?.Price
    </td>
</tr>
How to Use the Partial Views in ASP.NET Core MVC Application?

There are many methods available to render a partial view from our main view, and we are going to discuss all those methods in detail in our next article. Now, let us understand the syntax to render the Partial View from the Main view or child view:

  • Using Html.Partial or Html.RenderPartial methods: These methods are called within a view to render a partial view synchronously. Html.Partial returns an IHtmlString that can be rendered in a view, while Html.RenderPartial writes directly to the response stream, which can improve performance. Example: @Html.Partial(“_ProductDetails”, model)
  • Using Html.PartialAsync or Html.RenderPartialAsync methods: These are the asynchronous counterparts of the above methods and are recommended when the partial view is performing I/O operations. Example: await Html.RenderPartialAsync(“_ProductDetails”, model)
  • Using Tag Helpers: ASP.NET Core also supports rendering partial views using Tag Helpers, which can be more readable and easier to use, especially for those familiar with HTML. Example: <partial name=”_ProductDetails” model=”Model” />

So, let us render the partial view in this example using the partial helper method. To this HTML Helper method, we need to Pass the name of the partial view as a parameter. As our partial view, expecting the Product object, we need to pass the Product model as the second parameter, such as @await Html.PartialAsync(“_ProductDetails”, Model). So, modify the Details.cshtml View as follows.

@model PartialViewInMVC.Models.Product

@{
    ViewData["Title"] = "Details";
}
<div>
    <h4>Product Details</h4>

    <table class="table">
        <tr>
            <th>
                ProductID
            </th>
            <th>
                Name
            </th>
            <th>
                Category
            </th>
            <th>
                Description
            </th>
            <th>
                Price
            </th>
        </tr>

        @await Html.PartialAsync("_ProductDetails", Model)
    </table>
</div>

Now, 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 details should be rendered, the only View you need to change is the _ProductDetails.cshtml partial view. The above @Html.PartialAsync helper method passed a Product object to the “_ProductDetails” partial view. The partial view was dynamically rendered.

How to use the Partial Views in ASP.NET Core MVC Application?

Now, let us see how we can use the same Partial View from another View. Let us first modify the Product Controller as follows. Here, you can see we have added the Index action method, which is going to render all the product details.

using Microsoft.AspNetCore.Mvc;
using PartialViewInMVC.Models;

namespace PartialViewInMVC.Controllers
{
    public class ProductController : Controller
    {
        private List<Product> products = new List<Product>();
        public ProductController()
        {
            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}
            };
        }

        public ActionResult Index()
        {
            return View(products);
        }
        
        public ActionResult Details(int Id)
        {
            var ProductDetails = products.FirstOrDefault(prd => prd.ProductID == Id);
            return View(ProductDetails);
        }
    }
}

Next, add the Index.cshhtml view within the Views => Product folder. Once you add the view, copy and paste the following code. You will get any data if you use the PartialAsync within a for-each loop. So, here, instead of PartialAsync, we are using the Partial method.

@model IEnumerable<PartialViewInMVC.Models.Product>

@{
    ViewData["Title"] = "Index";
}

<h4>Product List</h4>

<table class="table">
    <tr>
        <th>
            ProductID
        </th>
        <th>
            Name
        </th>
        <th>
            Category
        </th>
        <th>
            Description
        </th>
        <th>
            Price
        </th>
    </tr>

    @foreach (var item in Model)
    {
        Html.Partial("_ProductDetails", item);
    }
</table>

As you can see in the above code, each loop item calls the same partial view by passing the product object, which will act as the model in the partial view. With the above changes in place, run the application and navigate to the Product/Index action method, and you will see the data as expected, as shown in the image below.

How to use the Partial Views in ASP.NET Core MVC Application?

Microsoft does not recommend using HTML.Partial method. You might encounter application deadlocks, in which case you will receive one warning message, as shown in the image below.

How to use the Partial Views in ASP.NET Core MVC Application?

It is saying that instead of Partial Method, please use Partial Tag helper. So, what is Tag helper that we will discuss in our upcoming article? Now, let us use the Partial Tag helper to render the Partial View in ASP.NET Core MVC Application.

The Partial Tag Helper achieves the same asynchronous rendering behavior as the PartialAsync HTML Helper. So, modify the Index View of the Product Controller as follows. The model attribute is assigned a Product instance for binding to the partial view.

@model IEnumerable<PartialViewInMVC.Models.Product>

@{
    ViewData["Title"] = "Index";
}

<h4>Product List</h4>

<table class="table">
    <tr>
        <th>
            ProductID
        </th>
        <th>
            Name
        </th>
        <th>
            Category
        </th>
        <th>
            Description
        </th>
        <th>
            Price
        </th>
    </tr>

    @foreach (var product in Model)
    {
        <partial name="_ProductDetails" model="product" />
    }
</table>

With the above changes in place, run the application, and you should get the output as expected.

In the next article, I will discuss Different ways to Render Partial Views in ASP.NET Core MVC Applications with Examples. In this article, I will try to explain Partial Views in ASP.NET Core MVC Applications with Examples. I hope you enjoy this Partial Views in ASP.NET Core MVC article.

Leave a Reply

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