Back to: ASP.NET Core Tutorials For Beginners and Professionals
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 a Partial View in ASP.NET Core MVC?
A Partial View in ASP.NET Core MVC is a reusable View Component that can be embedded within other views. It is essentially a smaller view or part of a view rendered inside a parent view. Partial Views are useful when we want to break down large views into smaller, manageable components that can be reused across different views in our application.
- Partial Views are similar to regular views but do not have a layout by default.
- They typically render a portion of the view or page, like headers, footers, forms, or other sections.
- You can pass data to Partial Views using the parent model or passing a separate one.
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 simplifies rendering partial views directly within Razor views. Instead of using the HTML Helper Methods (such as Html.Partial, Html.RenderPartial, Html.PartialAsync, and Html.RenderPartialAsync) in Razor views, the Partial Tag Helper provides a cleaner and more expressive HTML-like syntax to render the Partial Views.
How Do We Use Partial Tag Helper in ASP.NET Core MVC?
To use the Partial Tag Helper, we need to follow the following steps:
Create the Partial View:
Define the partial view in the Views/Shared folder or any other folder under Views. Ensure the partial view has a name starting with an underscore (e.g., _UserProfilePartial.cshtml, _FooterPartial.cshtml).
Use the Partial Tag Helper in Your Main View:
In the main view where you want to include the partial view, use the <partial> tag helper. If you need to pass a model to the Partial View, use the model attribute within the Partial Tag Helper, as shown in the below example:
<partial name=”_UserProfilePartial” model=”@Model.UserProfile” />
Rendering Without a Model: If the partial view does not require any specific model, you can render it like the below example:
<partial name=”_FooterPartial” />
Note: The name attribute specifies the name of the partial view, and the model attribute provides the model data to be used within it.
Partial Tag Helper Real-Time Example in ASP.NET Core MVC:
Let us understand Partial Tag Helper with one Real-Time Example in an ASP.NET Core MVC Application. In this application, we will implement three partial views using the Partial Tag Helper. One partial view will use model data, and the other two partial views will be static without any model data.
We have an application that displays a list of products on a page. We will include a footer and a header that is consistent across all pages. The product list will be rendered via a partial view that receives model data, while the footer and header will be rendered via partial views that do not need any model data.
First, create a new ASP.NET Core Project using the Model View Controller Template and name it PartialTagHelperDemo.
Create the Model:
First, create a class file named Product.cs within the Models folder and then copy and paste the following code. This model will be used to pass data to the partial view that displays the product list.
namespace PartialTagHelperDemo.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public decimal Price { get; set; } public string ImageUrl { get; set; } public string Category { get; set; } public bool InStock { get; set; } } }
Modify the Home Controller
Now, modify the HomeController as follows: We will generate some dummy product data and render the views.
using Microsoft.AspNetCore.Mvc; using PartialTagHelperDemo.Models; namespace PartialTagHelperDemo.Controllers { public class HomeController : Controller { public IActionResult Index() { var products = new List<Product> { new Product { Id = 1, Name = "Laptop", Description = "A powerful laptop for professionals Developere", Price = 999.99M, ImageUrl = "https://dummyimage.com/600x400/000/fff&text=Laptop", Category = "Electronics", InStock = true }, new Product { Id = 2, Name = "Smartphone", Description = "Latest smartphone with cutting-edge features", Price = 799.99M, ImageUrl = "https://dummyimage.com/600x400/000/fff&text=Smartphone", Category = "Electronics", InStock = true }, new Product { Id = 3, Name = "Headphones", Description = "Noise-cancelling over-ear headphones good for health", Price = 199.99M, ImageUrl = "https://dummyimage.com/600x400/000/fff&text=Headphones", Category = "Accessories", InStock = false } }; return View(products); } } }
Create the Partial Views
Next, we need to create three Partial Views inside the Views/Shared folder.
_ProductListPartial.cshtml (With Model Data)
This partial view will display the product list passed from the controller. It will display the product details, including the image, name, description, and price. We will also indicate whether the product is in stock. So, create the Partial view named _ProductListPartial.cshtml within the Views/Shared folder and then copy and paste the following code.
@model IEnumerable<Product> <div class="row"> @foreach (var product in Model) { <div class="col-md-4"> <div class="card mb-4"> <img class="card-img-top" src="@product.ImageUrl" alt="@product.Name"> <div class="card-body"> <h5 class="card-title">@product.Name</h5> <p class="card-text">@product.Description</p> <p class="card-text"><strong>Price: $@product.Price</strong></p> <p class="card-text"> @if (product.InStock) { <span class="badge badge-success">In Stock</span> } else { <span class="badge badge-danger">Out of Stock</span> } </p> </div> </div> </div> } </div>
_HeaderPartial.cshtml (Without Model Data)
This partial view will contain the static header section, which will be consistent across all pages. We will create a header partial view that includes a simple navigation bar with Bootstrap styling. So, create the Partial view named _HeaderPartial.cshtml within the Views/Shared folder and then copy and paste the following code.
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Product Store</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Products</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </nav>
_FooterPartial.cshtml (Without Model Data)
This partial view will contain the static footer section, which will be consistent across all pages. This partial view will contain a Bootstrap-styled footer with contact information and social media links. So, create the Partial view named _FooterPartial.cshtml within the Views/Shared folder and then copy and paste the following code.
<footer class="bg-light text-center text-lg-start"> <div class="container p-4"> <div class="row"> <div class="col-lg-6 col-md-12 mb-4 mb-md-0"> <h5 class="text-uppercase">Product Store</h5> <p>High-quality products at affordable prices. Shop with confidence!</p> </div> <div class="col-lg-3 col-md-6 mb-4 mb-md-0"> <h5 class="text-uppercase">Quick Links</h5> <ul class="list-unstyled"> <li><a href="#!" class="text-dark">About</a></li> <li><a href="#!" class="text-dark">Products</a></li> <li><a href="#!" class="text-dark">Contact</a></li> </ul> </div> <div class="col-lg-3 col-md-6 mb-4 mb-md-0"> <h5 class="text-uppercase">Follow Us</h5> <ul class="list-unstyled"> <li><a href="#!" class="text-dark">Facebook</a></li> <li><a href="#!" class="text-dark">Twitter</a></li> <li><a href="#!" class="text-dark">Instagram</a></li> </ul> </div> </div> </div> <div class="text-center p-3 bg-light"> © 2024 Product Store. All Rights Reserved. </div> </footer>
Update the _Layout.cshtml View
The layout view will contain the header and footer, which will be shared across all views in the application. So, modify the _Layout.cshtml View as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - PartialTagHelperDemo</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/PartialTagHelperDemo.styles.css" asp-append-version="true" /> </head> <body> <!-- Render Header --> <partial name="_HeaderPartial" /> <div class="container mt-4"> <!-- This will be replaced by view content --> @RenderBody() </div> <!-- Render Footer --> <partial name="_FooterPartial" /> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html>
Index.cshtml (Parent View with Partial Tag Helpers)
Finally, the Index view will include Product List partial views. So, modify the Index.cshtml View as follows:
@model IEnumerable<Product> @{ ViewData["Title"] = "Product Store"; } <h2>Welcome to Our Product Store</h2> <p>Find the best products at great prices.</p> <!-- Render Product List --> <partial name="_ProductListPartial" model="@Model" />
Run the Application
Once you have set up the views, controller, and model, run the application. You should see a beautifully designed product page, as shown in the image below.
Here, you can see
- A Header that includes navigation links.
- A Product List that displays detailed information about each product, including name, description, price, stock status, and an image.
- A Footer with company information and links.
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 Real-Time Examples. I hope you enjoy this article.