Back to: ASP.NET Core Tutorials For Beginners and Professionals
Partial Tag Helper in ASP.NET Core MVC
I will discuss the Partial Tag Helper in ASP.NET Core MVC Application with Examples in this article. Please read our previous article discussing Form Tag Helpers in ASP.NET Core MVC Application.
What is Partial Tag Helper in ASP.NET Core MVC
The Partial Tag Helper in ASP.NET Core MVC is a built-in Tag Helper that enables developers to render partial views directly within Razor views in a more HTML-like syntax. A partial view in ASP.NET Core MVC is a Razor markup file (.cshtml) that contains a segment of HTML content that can be used for rendering within other views, thereby promoting code reuse and modular design.
Tag Helpers, in general, are a feature of ASP.NET Core MVC that allows developers to embed server-side code to generate HTML, CSS, and JavaScript in Razor views in a way that resembles standard HTML tags, providing a clearer and more readable syntax compared to the traditional Razor HTML helpers.
Syntax:
Here’s how you can use the Partial Tag Helper:
<partial name="PartialViewName" />
This is equivalent to the older Razor syntax:
@Html.Partial("PartialViewName")
Attributes for the Partial Tag Helper:
- name: The name of the partial view. This is a mandatory attribute.
- model: The model you want to pass to the partial view. It’s optional.
- view-data: Any additional view data you want to pass to the partial view.
- fallback-name: The name of the partial view that will be used if the specified partial view in the name isn’t found.
- fallback-view-data: The view data passed to the fallback partial view if it’s used.
- render-mode: Specifies whether the partial rendering should be synchronous or asynchronous.
How to use Partial Tag Helper in ASP.NET Core MVC?
To use the Partial Tag Helper in ASP.NET Core MVC, follow these steps:
Ensure Tag Helpers Are Registered:
First, ensure you’ve registered the Tag Helpers in the _ViewImports.cshtml file. This file typically resides in the Views folder of your project. If you haven’t done this yet, add the following line:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Create a Partial View:
Let’s say you want to create a reusable navigation menu. Create a file named _NavigationMenu.cshtml in the Views/Shared directory. This will be your partial view. Once you create the _NavigationMenu.cshtml Partial View, then copy and paste the following code into it:
<nav> <ul> <li><a href="/Home">Home</a></li> <li><a href="/About">About</a></li> <li><a href="/Contact">Contact</a></li> </ul> </nav>
Using Partial Tag Helper:
Now, in any of your primary views or layouts where you wish to include this navigation menu, you can use the Partial Tag Helper as follows:
<partial name="_NavigationMenu" />
Additional Attributes:
model: If your partial view expects a model, you can pass it using the model attribute:
<partial name="_PartialViewName" model="YourModelInstance" />
view-data: If you want to pass additional view data to the partial view.
<partial name="_PartialViewName" view-data="ViewDataDictionaryInstance" />
fallback-name: Specifies an alternative partial view name if the primary one isn’t found.
<partial name="_PartialViewName" fallback-name="_FallbackPartialViewName" />
fallback-view-data: View data for the fallback partial view.
<partial name="_PartialViewName" fallback-view-data="FallbackViewDataDictionaryInstance" />
render-mode: Defines whether the partial view should be rendered synchronously (Server) or asynchronously (ServerPrerendered). By default, it is ServerPrerendered, i.e., rendering asynchronously.
<partial name="_PartialViewName" render-mode="ServerPrerendered" />
If you have an async partial view (a view that performs asynchronous operations), you can render it with the render-mode attribute set to ServerPrerendered. This will ensure that the view is rendered asynchronously. Here, render-mode can be one of the following:
- Server (default): Renders the partial view synchronously.
- ServerPrerendered: Renders the partial view asynchronously.
By following these steps, you can efficiently use the Partial Tag Helper in your ASP.NET Core MVC project to render partial views, making your views more modular and your code more reusable.
Partial Tag Helper Example in ASP.NET Core MVC:
Let’s understand the usage of the built-in Partial Tag Helper in ASP.NET Core MVC Application with an example. Imagine you are building a web application that displays blog posts. Each blog post has a comment section. To modularize the views, you’ve decided to put the comments section into a partial view. Let us understand How we can implement this using the Partial Tag Helper.
Creating Models:
We are going to use the following BlogPost and Comment models:
Comment.cs
Create a class file with the name Comment.cs within the Models folder, and then copy and paste the following code into it.
namespace TagHelpersDemo.Models { public class Comment { public string? Author { get; set; } public string? Text { get; set; } } }
BlogPost.cs
Create a class file named BlogPost.cs within the Models folder, then copy and paste the following code into it.
namespace TagHelpersDemo.Models { public class BlogPost { public int Id { get; set; } public string? Title { get; set; } public string? Content { get; set; } public List<Comment>? Comments { get; set; } } }
Creating Partial View:
Create a partial view named _Comments.cshtml in the Views/Shared folder and then copy and paste the following code into it.
@model List<Comment> <div> @foreach (var comment in Model) { <div class="comment"> <strong>@comment.Author</strong>: @comment.Text </div> } </div>
Modifying Controller:
Next, modify the Home Controller as follows. As you can see, the Index Action method returns the BlogPost view:
using Microsoft.AspNetCore.Mvc; using TagHelpersDemo.Models; namespace TagHelpersDemo.Controllers { public class HomeController : Controller { public IActionResult BlogPost(int id) { //In Real-Time, you will get the data from the database //Here, we have hardcoded the data var post = new BlogPost { Id = id, Title = "What is ASP.NET Core", Content = "ASP.NET Core (.NET) is a free, open-source, and cloud-optimized framework that can run on Windows, Linux, or macOS.", Comments = new List<Comment> { new Comment { Author = "Pranaya", Text = "Great post!" }, new Comment { Author = "Kumar", Text = "Thanks for sharing." }, new Comment { Author = "Rout", Text = "Appreciate your work..." } } }; return View(post); } } }
Creating Main View (BlogPost.cshtm):
Create a new View with the name BlogPost.cshtm within the Views => Home folder, then copy and paste the following code into it. In the main view where we want to display the blog post, we can use the Partial Tag Helper to display the comments.
@model BlogPost @{ ViewData["Title"] = "BlogPost"; } <h2>@Model.Title</h2> <p>@Model.Content</p> <!-- Embedding the partial view --> <partial name="_Comments" model="Model.Comments" />
Now, run the application and navigate to Home/BlogPost with the route value, and you should see the output as expected, as shown in the below image.
When To Use Partial Tag Helper in ASP.NET Core MVC?
In ASP.NET Core MVC, the Partial Tag Helper offers a more declarative way to render partial views than traditional Razor methods. Deciding when to use it depends on the context and desired outcomes. Here are some situations where using the Partial Tag Helper can be beneficial:
- Readability: If you prefer a more HTML-centric syntax in your views, the Partial Tag Helper provides a clearer separation between HTML and C# code. This can make your views more readable, especially for front-end developers who might not be familiar with Razor syntax.
- Modularity: When you have common components or UI pieces that are reused across multiple views, partial views can help modularize your views.
- Maintainability: By breaking down complex views into smaller partial views, it becomes easier to maintain and update specific sections of your web pages without affecting the entire view.
- Dynamic Content Loading: If certain portions of your view are dynamically loaded based on some logic (e.g., user roles, feature toggles, etc.), using partial views can help isolate these sections. The Partial Tag Helper makes incorporating these dynamic sections straightforward.
- Layouts and Templating: For consistent layout components such as headers, footers, navigation bars, etc., using partial views can ensure consistency across your application. While layouts in Razor already help with this, partial views and the Partial Tag Helper can be beneficial for more granular components.
- Loading Data-Driven Components: Sometimes, specific sections of a view might be driven by data different from the view’s primary model. By using partial views (and possibly their own specific models), you can encapsulate these data-driven UI components effectively. The Partial Tag Helper then offers a clean way to include these in your main view.
- Async Rendering: The Partial Tag Helper supports asynchronous rendering using the render-mode attribute. If you need to load some parts of your view asynchronously for performance or other reasons, the Partial Tag Helper can facilitate this.
When Not to Use Partial Tag Helper in ASP.NET Core MVC?
While the Partial Tag Helper can be very useful, it’s essential to be cautious and not overuse it. Breaking views into many small partials can sometimes harm performance, as each partial view invocation carries a bit of overhead. Furthermore, excessive use can lead to an architecture that’s hard to follow if there’s no clear structure or reasoning behind the organization of partials.
Real-Time Use Cases of Partial Tag Helper in ASP.NET Core MVC
In ASP.NET Core MVC, the Partial Tag Helper aids in the rendering of partial views in a more HTML-like manner. Partial views are essentially segments of markup and code designed to be reusable across different views. Here are some practical use cases for the Partial Tag Helper:
Page Layout Components:
- Headers and Footers: For consistent presentation across your site.
- Navigation Menus: To maintain a consistent navigation structure.
- Sidebars: Displaying widgets or other consistent sidebar content.
Forms and Form Components:
- Reusable Form Segments: If you have parts of forms (like address entry and user contact details) that appear in multiple forms.
- Captcha: Integration of CAPTCHA in multiple forms across the site.
Modals and Dialogs:
- For pop-ups, info dialogs, and confirmation boxes that could be used in multiple places.
User-Related Components:
- User Profile Snippets: Displaying a user’s mini-profile or avatar in different sections of a site.
- Login/Logout Panel: A consistent way to display user login status across pages.
Comments and Discussion Threads:
- For blog posts, articles, or any content type that supports user comments or discussions.
Advertisements and Promotions:
- If you have recurring ad or promotion spaces on your site.
Dynamic Content:
- Dashboard Widgets: For applications with dashboards that have customizable widgets.
- Recommendations: Dynamic content recommendations based on user behavior or preferences.
Data Tables and Listings:
- Pagination Controls: If you display lists of data with pagination.
- Sorting and Filtering Controls: For data tables that have these features.
Feedback and Ratings:
- Modules for users to leave feedback or rate items used in multiple areas like product pages, blog posts, etc.
The advantage of the Partial Tag Helper in these use cases is that it offers a more declarative, HTML-centric way to embed these components, making Razor views clearer and more modular. This enhances the maintainability and reusability of the code while providing a more intuitive way for developers (especially those who might be more comfortable with HTML than Razor syntax) to understand the structure and components of the view.
So, the Partial Tag Helper in ASP.NET Core MVC provides a cleaner and more intuitive way to render partial views within Razor views, promoting a modular and DRY (Don’t Repeat Yourself) approach to web application development.
In the next article, I will discuss Creating a Custom Tag Helper in AS.NET Core MVC Applications. In this article, I try to explain Partial Tag Helper in ASP.NET Core MVC Application with Examples. I hope you enjoy this Partial Tag Helper in ASP.NET Core MVC article.