Partial Tag Helper in ASP.NET Core MVC

Partial Tag Helper in ASP.NET Core MVC

In this article, I will discuss the Partial Tag Helper in ASP.NET Core MVC Application with Examples. 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, promoting code reuse and modular design.

This feature can help break down complex views into simpler, reusable components. Partial views are similar to regular views but intended to render a portion of the HTML content that can be reused across different views.

Syntax:

Here’s how you can use the Partial Tag Helper:

<partial name="PartialViewName" />

Here, the name specifies the partial view to render

How Do We 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 are registered Tag Helpers in the _ViewImports.cshtml file. This file typically resides in your project’s Views folder. 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 in ASP.NET Core MVC:

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 of Partial Tag Hellper:

model: The model you want to pass to the partial view. It’s optional. If your partial view expects a model, you can pass it using the model attribute:

<partial name="_PartialViewName" model="YourModelInstance" />

view-data: Any additional view data you want to pass to the partial view.

<partial name="_PartialViewName" view-data="ViewDataDictionaryInstance" />

fallback-name: The name of the partial view that will be used if the specified partial view in the name isn’t found.

<partial name="_PartialViewName" fallback-name="_FallbackPartialViewName" />

fallback-view-data: The view data passed to the fallback partial view if it’s used.

<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" />

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 reusable.

Partial Tag Helper Real-Time Example in ASP.NET Core MVC:

Let’s understand the usage of the built-in Partial Tag Helper in an 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 have decided to put the comments section into a partial view. Let’s 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? Email { get; set; }
        public string? Name { 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? Author { 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.Name - @comment.Email</strong>: @comment.Text
        </div>
    }
</div>
Modifying Controller:

Next, modify the HomeController 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 = 1000)
        {
            //In Real-Time, you will get the data from the database
            //Here, we have hard coded the data
            var post = new BlogPost
            {
                Id = id,
                Title = "What is ASP.NET Core",
                Author = "Pranaya Rout",
                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 { Name = "James", Email = "James@Example.com", Text = "Great post!" },
                    new Comment { Name = "Kumar", Email = "Kumar@Example.com", Text = "Thanks for sharing." },
                    new Comment { Name = "Rout", Email = "Rout@Example.com", Text = "Appreciate your work..." }
                }
            };

            return View(post);
        }
    }
}
Creating Main View (BlogPost.cshtm):

Create a new View with the name BlogPost.cshtml within the Views => Home folder, and copy and paste the following code. 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";
    Layout = null;
}

<h3>Title: @Model.Title </h3>
<h3>Author: @Model.Author </h3>
<p>@Model.Content</p>

<!-- Embedding the partial view -->
<partial name="_Comments2" fallback-name="_NavigationMenu" model="Model.Comments" render-mode="ServerPrerendered" />

Now, run the application and navigate to Home/BlogPost with the route value. You should see the output as expected, as shown in the image below.

Partial Tag Helper in ASP.NET Core MVC Application with Examples

Real-Time Use Cases of Partial Tag Helper in ASP.NET Core MVC

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:

  • 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.
  • 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.
  • Pop-ups: For pop-ups, info dialogs, and confirmation boxes that could be used in multiple places.
  • Login/Logout Panel: A consistent way to display user login status across pages.
  • Feedback: Modules for users to leave feedback or rate items used in multiple areas, such as product pages, blog posts, etc.

The Partial Tag Helper provides a cleaner and more HTML-Centric 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 will try to explain Partial Tag Helper in ASP.NET Core MVC Application with examples. I hope you enjoy this article.

Leave a Reply

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