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?

Partial views in ASP.NET Core MVC are a powerful feature for breaking down complex views into more manageable pieces. They allow for modular development of web pages by enabling the reuse of view components across different parts of an application. This not only enhances code readability and maintainability but also promotes DRY (Don’t Repeat Yourself) principles in web development.

They are similar to traditional views, but partial views are intended for reusing sections of web pages across different views. They do not run on their own; instead, they must be invoked from other views or layouts.

A partial view is a Razor markup file (.cshtml) that renders HTML output within another markup file’s rendered output. They are not served directly by controllers; instead, they are used within views to modularize view content. 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. This helps in maintaining and organizing views 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:

We need to develop a partial view when we need a common part of the user interface on multiple pages in a web application. Sometimes, we also use partial views to divide a web page into small parts such as header, footer, and menus, which we can use in the Layout Page. Other examples are comments on the blogging site, shipping and billing address in the invoice on an e-commerce site, etc. Partial views are used for code re-usability purposes.

Let us understand Partial Views in ASP.NET Core MVC Application with an example. First, Let us create a new ASP.NET Core MVC Web Application named “PartialViewInMVC” using the Model View Controller Project Template.

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.

Creating Product Model:

Create a class file with the name Product.cs within the Models folder, then copy and paste the following code. This simple class has 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) in several different places or pages, we must create and use them as Partial Views in the ASP.NET Core MVC Application.

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 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?

Partial views can significantly improve code reusability and maintainability by encapsulating specific functionality or UI components. They help keep your codebase clean and promote the separation of concerns within your 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 get application deadlocks; in this case, you will get 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.

Why do we need Partial Views in the ASP.NET Core MVC Application?

Partial views serve several important purposes in an ASP.NET Core MVC application, providing benefits that contribute to better organization, reusability, and maintainability of your codebase. Here’s why you might need partial views in your ASP.NET Core MVC application:

  1. Modularization and Reusability: Partial views allow you to break down complex views into smaller, reusable components. This modularity makes it easier to manage and maintain your code by isolating different sections of a page as separate components. These components can be reused across multiple views, promoting a more consistent user interface and reducing code duplication.
  2. Separation of Concerns: Using partial views encourages the separation of concerns within your application. You can isolate specific functionality or UI elements into their own partial views, which helps maintain a clean and organized codebase. Developers can focus on implementing and maintaining smaller, focused components without worrying about the entire view.
  3. Code Organization: Managing large, monolithic views can become challenging as your application grows. Partial views allow you to organize your codebase into smaller, manageable files. This makes it easier to locate, update, and debug specific parts of your application’s user interface.
  4. Maintenance and Updates: With partial views, you can update a specific component without affecting the entire view. This makes maintenance and updates more focused and reduces the risk of introducing unintended side effects.
  5. Performance Optimization: In cases where certain sections of a page are loaded dynamically or conditionally, using partial views can help optimize performance by rendering only the necessary parts of the page. This can lead to faster load times and a better user experience.
When Should We Use Partial Views in ASP.NET Core MVC Application?

Here are some scenarios where you should consider using partial views:

  1. Repeating UI Components: When you have UI components that appear across multiple views or pages, such as headers, footers, navigation menus, or sidebars, use partial views. This ensures a consistent user experience throughout your application.
  2. Complex Views: If you have large and complex views that are difficult to manage or debug, consider breaking them down into smaller, more manageable components using partial views. This promotes a more modular and organized codebase.
  3. Form Elements: Use partial views for complex form elements across multiple forms. For instance, if you have a custom date picker or a multi-step form, encapsulating them in partial views can improve code reuse and maintenance.
  4. Dynamic Content: When you dynamically load or update certain page parts based on user interactions (e.g., via AJAX), partial views can help you render and manage those dynamic components effectively.
  5. Custom Controls: If your application requires custom controls or user interface elements that are not readily available in HTML or standard libraries, partial views allow you to create and manage these components independently.

In the next article, I am going to discuss Different ways to Render Partial Views in ASP.NET Core MVC Applications with Examples. In this article, I 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 *