Back to: ASP.NET Core Tutorials For Beginners and Professionals
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 way to modularize and reuse parts of your views across different views or layouts. They allow us to break down complex views into smaller, more manageable components, making our code more organized, maintainable, and easier to update. Partial views can represent a portion of a page’s content, such as a sidebar, a header, a footer, or any other reusable UI component.
That means the Partial Views in ASP.NET Core MVC Application are the views that are rendered within another view (either content view or layout view). The HTML output generated by the partial view is rendered into the calling (or parent) view. Like views, partial views use the “.cshtml” file extension.
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. Partial views help us to reduce code duplication.
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 folderthen copy and paste the following code into it. Thissimple class withhaving 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 wouthing like the one below.
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 wamodify anythingcation, we need to do it in all places. This is where Partial Views Comes into the picture in ASP.NET MVC Application.
Creating Product Controller:
Add a new Contrnamede name ProductController within the Controllers folder, and choose the “MVC Controller – Empty” template. Once you Create the ProductControlthen 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 navigates to Product/Details/1, and you should get the following output.
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 ASP.NET Core MVC Application.
How to 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.
Right-click on the /Views/Shared folder, then select Add -> View option from the context menu. It will open the following window. Here, we must select Razor View and click the Add button, as shown in the image below.
Once you click on the Add button, it will open the following window, and here, please provide the View name as _ProductDetails details, check the Create as a partial view check box, and then click on the Add button as shown in the below image.
Once you create the _ProductDetails.cshtml Partial View then opens the view file and copies and pastes the following code into it. 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 all those methods we are going to discuss in our next article. So, in this article, let us understand how we can render a partial view using the Partial helper method.
We can render the partial view from our main views 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, so 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.
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 navigates to the Product/Index action method, and you will see the data as expected, as shown in the below image.
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.
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:
- 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.
- 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.
- 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.
- Collaboration: Using partial views can improve collaboration when working on a project with multiple developers or teams. Different teams can work on different components without interfering with each other’s code as long as they adhere to the agreed-upon contracts for the partial views.
- 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.
- Improved Testing: Smaller, modular components are generally easier to test in isolation. Partial views allow you to write unit tests for individual components, enhancing your application’s overall testability and reliability.
- 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.
- Encapsulation of Logic: Partial views can encapsulate both presentation and some logic related to the component they represent. This can help maintain a clean separation between your views and controllers while allowing for a degree of encapsulated functionality.
- Consistency and Branding: If your application has a consistent layout or branding elements that need to be repeated across different views, partial views can ensure that these elements are applied consistently throughout the application.
Overall, partial views enhance the maintainability, scalability, and overall structure of your ASP.NET Core MVC application. By leveraging partial views effectively, you can create a more modular and organized codebase that is easier to develop, test, and maintain over time.
When Should We Use Partial Views in ASP.NET Core MVC Application?
Partial views in an ASP.NET Core MVC application should be used strategically to enhance code organization, reusability, and maintainability. Here are some scenarios where you should consider using partial views:
- 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 consistent branding and user experience throughout your application.
- 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.
- Widget-Like Functionality: When you want to create reusable “widget-like” components that encapsulate both UI and functionality, partial views can be beneficial, for example, a weather widget, news feed, or user profile summary.
- Different Layouts: When different sections of a page have distinct layouts or formatting, partial views can help maintain separation and clarity. You can create separate partial views for each layout variation.
- Form Elements: Use partial views for complex form elements that are used 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.
- 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.
- 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.
- Team Collaboration: When working on larger projects with multiple developers or teams, partial views can facilitate parallel development by allowing teams to work on different components in isolation.
- Testing: If you want to write unit tests for specific UI components, using partial views can make it easier to isolate and test individual pieces of functionality.
- Consistency: Use partial views to ensure consistency in the look and behavior of specific UI elements across various parts of your application.
- Layout Variations: If your application requires different layout variations for different user roles or scenarios, partial views can help manage these variations in a structured manner.
Remember that while partial views provide numerous benefits, using them excessively can lead to unnecessary complexity. Consider the balance between reusability and maintainability and aim for a clean, logical structure in your application’s use of partial views. Use them when they genuinely enhance the development and maintenance process, and avoid over-engineering or overcomplicating your views.
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.