Back to: ASP.NET Core Tutorials For Beginners and Professionals
Real-Time Examples of Custom HTML Helpers in ASP.NET Core MVC
I will discuss Real-Time Examples of Custom HTML Helpers in ASP.NET Core MVC Applications with Examples in this article. Please read our previous article discussing How to Create Custom HTML Helpers in ASP.NET Core MVC.
Real-Time Examples of Custom HTML Helpers in ASP.NET Core MVC
In ASP.NET Core MVC, HTML helpers are methods you can use in Razor views to generate HTML content. The built-in HTML helpers are provided by the HtmlHelper class. However, you can also create custom HTML helpers by defining extension methods for the IHtmlHelper interface. Let us proceed and try to understand a few real-time examples of using Custom HTML Helpers in ASP.NET Core MVC Application.
Example1: Form Control with Validation
Often, form controls come with validation messages, tooltips, and specific CSS styles. Instead of repeating the same structure, a custom HTML helper can encapsulate this pattern. Example: An input field that automatically displays validation errors next to it
Let us create a Custom HTML Helper to render an input with validation attributes. So, create a class file with the name FormControlHelpers.cs within the Models folder and copy and paste the following code.
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; namespace HTML_HELPER.Models { public static class FormControlHelpers { public static IHtmlContent CustomInputWithValidation(this IHtmlHelper htmlHelper, string modelPropertyName, string labelText) { var fullHtml = $@" <div class='form-group'> <label for='{modelPropertyName}'>{labelText}</label> <input type='text' class='form-control' id='{modelPropertyName}' name='{modelPropertyName}' asp-for='{modelPropertyName}' /> <span asp-validation-for='{modelPropertyName}' class='text-danger'></span> </div>"; return new HtmlString(fullHtml); } } }
Next, modify the Home Controller as follows:
using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } } }
Next, modify the Index.cshtml view file as follows. As you can see, we are using the CustomInputWithValidation HTML Helper method here.
@Html.CustomInputWithValidation("UserName", "User Name")
Example2: Breadcrumb Helper
Displaying navigational breadcrumbs on a site can be streamlined using a custom helper that takes the current path or a list of paths and then renders the breadcrumb navigation.
Generate breadcrumb navigation based on the provided list of paths. So, create a class file with the name BreadcrumbHelpers.cs within the Models folder and copy and paste the following code.
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; using System.Text; namespace HTML_HELPER.Models { public static class BreadcrumbHelpers { public static IHtmlContent Breadcrumbs(this IHtmlHelper htmlHelper, List<(string Url, string Name)> paths) { var stringBuilder = new StringBuilder(); stringBuilder.Append("<nav aria-label='breadcrumb'>"); stringBuilder.Append("<ol class='breadcrumb'>"); foreach (var path in paths) { stringBuilder.AppendFormat("<li class='breadcrumb-item'><a href='{0}'>{1}</a></li>", path.Url, path.Name); } stringBuilder.Append("</ol></nav>"); return new HtmlString(stringBuilder.ToString()); } } }
Next, modify the Index.cshtml view as follows. As you can see, we are using the Breadcrumbs HTML Helper method here.
@{ var breadcrumbs = new List<(string Url, string Name)> { ("/", "Home"), ("/products", "Products"), ("/products/1", "Product 1") }; } @Html.Breadcrumbs(breadcrumbs)
Example3: SEO Meta Tag Helper
Helpers can be created to generate SEO-friendly meta tags, structured data, or other SEO-specific elements to be added to a page dynamically.
A helper that outputs meta tags for SEO. So, create a class file with the name SeoHelpers.cs within the Models folder and then copy and paste the following code.
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; namespace HTML_HELPER.Models { public static class SeoHelpers { public static IHtmlContent MetaDescription(this IHtmlHelper htmlHelper, string content) { return new HtmlString($"<meta name='description' content='{content}'>"); } } }
Next, modify the Index.cshtml view as follows. As you can see, we are using the MetaDescription HTML Helper method here.
@Html.MetaDescription("This is a sample page description for SEO.")
Example4: Theming Helper
When supporting multiple themes or brands, a custom helper can determine the current theme or brand and generate the appropriate CSS links, logos, and other related assets.
Render a CSS link based on the current theme. So, create a class file with the name ThemeHelpers.cs within the Models folder and then copy and paste the following code into it.
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; namespace HTML_HELPER.Models { public static class ThemeHelpers { public static IHtmlContent RenderThemeCss(this IHtmlHelper htmlHelper, string currentTheme) { var cssLink = $"/css/themes/{currentTheme}.css"; return new HtmlString($"<link rel='stylesheet' href='{cssLink}'>"); } } }
Next, modify the Index.cshtml view as follows. As you can see, we are using the RenderThemeCss HTML Helper method.
@Html.RenderThemeCss("dark-theme")
Example5: Pagination Controls
For displaying large lists, pagination is essential. A custom helper can generate a standard pagination control based on the current page, total items, and items per page. A helper to create pagination controls. So, create a class file named PaginationHelpers.cs within the Models folder and copy and paste the following code.
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; using System.Text; namespace HTML_HELPER.Models { public static class PaginationHelpers { public static HtmlString CreatePagination(this IHtmlHelper htmlHelper, int currentPage, int totalPages) { StringBuilder result = new StringBuilder(); result.Append("<nav><ul class='pagination'>"); for (int i = 1; i <= totalPages; i++) { if (i == currentPage) { result.Append($"<li class='page-item active'><span class='page-link'>{i}</span></li>"); } else { result.Append($"<li class='page-item'><a class='page-link' href='?page={i}'>{i}</a></li>"); } } result.Append("</ul></nav>"); return new HtmlString(result.ToString()); } } }
Next, modify the Index.cshtml view as follows. As you can see here, we are using the CreatePagination HTML Helper method.
@Html.CreatePagination(2, 10)
Example6: Dynamic Menus
Menus that change based on user roles, permissions, or other criteria can be encapsulated within a custom HTML helper, ensuring consistent rendering across views.
Dynamic Menus using Custom HTML Helper Methods in ASP.NET Core MVC. Dynamic menus often depend on user roles, permissions, or other dynamic criteria. You can consistently generate these menus across views using a custom HTML helper. Here’s an example of creating and using a custom HTML helper to generate dynamic menus in ASP.NET Core MVC.
Step 1: Define Your Menu Model
First, let’s create a class file with the name MenuItem.cs within the Models folder and then copy and paste the following code into it. This is a simple model for menu items:
namespace HTML_HELPER.Models { public class MenuItem { public string Text { get; set; } public string Url { get; set; } public bool IsActive { get; set; } public List<MenuItem> SubItems { get; set; } = new List<MenuItem>(); } }
Step 2: Create a Custom HTML Helper for the Dynamic Menu
Next, create another class file with the name MenuHtmlHelpers.cs within the Models folder and copy and paste the following code into it. This helper will generate the necessary HTML based on a list of MenuItem:
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; using System.Text; namespace HTML_HELPER.Models { public static class MenuHtmlHelpers { public static HtmlString DynamicMenu(this IHtmlHelper htmlHelper, List<MenuItem> menuItems) { StringBuilder result = new StringBuilder(); result.Append("<ul class='menu'>"); foreach (var item in menuItems) { result.AppendFormat("<li class='{0}'>", item.IsActive ? "active" : ""); result.AppendFormat("<a href='{0}'>{1}</a>", item.Url, item.Text); if (item.SubItems.Count > 0) { result.Append("<ul class='submenu'>"); foreach (var subItem in item.SubItems) { result.AppendFormat("<li class='{0}'><a href='{1}'>{2}</a></li>", subItem.IsActive ? "active" : "", subItem.Url, subItem.Text); } result.Append("</ul>"); } result.Append("</li>"); } result.Append("</ul>"); return new HtmlString(result.ToString()); } } }
Step 3: Use the Custom HTML Helper in a Razor View
Let’s say you’ve populated a List<MenuItem> based on some logic (e.g., user permissions). You can then pass this list to the custom helper to generate the dynamic menu. So, modify the Index.cshtml file as shown below.
@using HTML_HELPER.Models @model List<MenuItem> @Html.DynamicMenu(Model)
Step 4: Populate the List<MenuItem> Dynamically
The actual list of MenuItem objects might be generated in your controller based on user roles, permissions, or other criteria, and here we have hard-coded the same. So, modify the Home Controller class as follows.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public IActionResult Index() { List<MenuItem> menu = new List<MenuItem> { new MenuItem { Text = "Home", Url = "/Home/Index", IsActive = true }, new MenuItem { Text = "Admin", Url = "/Admin", SubItems = new List<MenuItem> { new MenuItem { Text = "Users", Url = "/Admin/Users" }, new MenuItem { Text = "Settings", Url = "/Admin/Settings", IsActive = true } } } }; return View(menu); } } }
In this example, the Index method populates the menu and passes it to the view. The view then uses the custom HTML helper to render the dynamic menu. This approach allows you to adapt and extend the menu generation logic to fit various scenarios and requirements.
Example7: Reusable Widgets
Components like sidebars, content cards, or user profile boxes that appear across various views can be generated using custom HTML helpers. Using custom HTML helpers to create reusable widgets is a great way to maintain a clean and organized codebase and ensure consistent rendering across views. Here’s an example to demonstrate creating and using such reusable widgets.
Example: Profile Card Widget
Imagine you have a profile card that displays a user’s name, profile image, and a short bio. This card might be reused in different parts of your website: user lists, comments section, article authors, etc.
Define a Model for the Profile Card
First, let’s create a simple model for the profile card. So, create a class file with the name ProfileCardModel.cs within the Models folder and copy and paste the following code into it.
namespace HTML_HELPER.Models { public class ProfileCardModel { public string Name { get; set; } public string ProfileImageUrl { get; set; } public string Bio { get; set; } } }
Define Custom HTML Helper:
Create the Custom HTML Helper for the Profile Card. So, create a class file with the name WidgetHtmlHelpers.cs within the Models folder and copy and paste the following code into it.
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; using System.Text; namespace HTML_HELPER.Models { public static class WidgetHtmlHelpers { public static HtmlString ProfileCard(this IHtmlHelper htmlHelper, ProfileCardModel model) { StringBuilder result = new StringBuilder(); result.Append("<div class='profile-card'>"); result.AppendFormat("<img src='{0}' alt='{1}' class='profile-img'/>", model.ProfileImageUrl, model.Name); result.AppendFormat("<h2>{0}</h2>", model.Name); result.AppendFormat("<p>{0}</p>", model.Bio); result.Append("</div>"); return new HtmlString(result.ToString()); } } }
Using the Custom HTML Helper
Use the Custom HTML Helper in a Razor View. So, modify the Index.cshtml file as follows. To use the profile card widget, we can invoke the custom helper:
@using HTML_HELPER.Models @model ProfileCardModel @Html.ProfileCard(Model)
Modifying Home Controller:
We need to populate the ProfileCardModel from our controller and send it to the view. So, modify the Home Controller class as follows.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public IActionResult Index() { ProfileCardModel model = new ProfileCardModel { Name = "Pranaya Rout", ProfileImageUrl = "/path/to/image.jpg", Bio = "Software Developer at ABC Corp." }; return View(model); } } }
Benefits:
- Consistency: By defining the widget’s structure and styling in one place, you ensure it looks and behaves consistently everywhere it’s used.
- Easier Maintenance: Changes to the widget (e.g., adding an email field) only need to be made in one location.
- Cleaner Views: Your Razor views are tidier as they can leverage the helper instead of repeating HTML structures.
- Flexibility: By designing your widgets to accept configurations or additional parameters, you can make them versatile to handle different scenarios or styles.
Remember, if the widget becomes too complex, or you want to utilize more MVC features, turning the widget into a View Component might be better than using an HTML helper. View Components in ASP.NET Core allow you to encapsulate view and logic into a reusable unit, which is perfect for complex widgets.
Example8: Configurable Data Tables
A table displaying data from various sources with options for sorting, filtering, and specifying columns. A custom helper can take in this configuration and render the table accordingly.
Creating configurable data tables using custom HTML helper methods can provide a flexible and reusable way to display tabular data across your application. Here’s a basic example to illustrate the process.
Define a Model for the Data Table Configuration
Firstly, define the configuration for the data table, specifying the columns you want to display and any other properties you may need. So, create a class file with the name DataTableConfig.cs within the Models folder and copy and paste the following code into it.
namespace HTML_HELPER.Models { public class DataTableConfig { public List<string> Columns { get; set; } public string TableClass { get; set; } = "table"; // default CSS class } }
Create another class file named MyCustomDataType.cs and copy and paste the following code into it. This is the class that is going to hold the model data.
namespace HTML_HELPER.Models { public class MyCustomDataType { public string Name { get; set; } public int Age { get; set; } public string Address { get; set; } } }
Create the Custom HTML Helper for the Data Table
Next, design your custom HTML helper. So, create a class file named DataTableHtmlHelpers.cs within the Models folder and copy and paste the following code into it.
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; using System.Text; namespace HTML_HELPER.Models { public static class DataTableHtmlHelpers { public static HtmlString DataTable<T>(this IHtmlHelper htmlHelper, IEnumerable<T> data, DataTableConfig config) { StringBuilder result = new StringBuilder(); // Table start result.AppendFormat("<table class='{0}'>", config.TableClass); // Header result.Append("<thead><tr>"); foreach (var column in config.Columns) { result.AppendFormat("<th>{0}</th>", column); } result.Append("</tr></thead>"); // Body result.Append("<tbody>"); foreach (var item in data) { result.Append("<tr>"); foreach (var column in config.Columns) { var value = item.GetType().GetProperty(column)?.GetValue(item, null); result.AppendFormat("<td>{0}</td>", value); } result.Append("</tr>"); } result.Append("</tbody>"); // Table end result.Append("</table>"); return new HtmlString(result.ToString()); } } }
Use the Custom HTML Helper in a Razor View
Now, you can use the data table widget in a Razor view. So, modify the Index.cshtml file as follows.
@using HTML_HELPER.Models @model IEnumerable<MyCustomDataType> @{ var config = new DataTableConfig { Columns = new List<string> { "Name", "Age", "Address" } }; } @Html.DataTable(Model, config)
Modifying Home Controller:
From your controller, you need to populate a list of MyCustomDataType and send it to the view. So, modify the Home Controller as follows.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public IActionResult Index() { List<MyCustomDataType> data = new List<MyCustomDataType> { new MyCustomDataType { Name = "Pranaya", Age = 35, Address = "123 ABC St." }, new MyCustomDataType { Name = "Kumar", Age = 34, Address = "456 PQR St." }, new MyCustomDataType { Name = "Rout", Age = 33, Address = "789 XYZ St." } }; return View(data); } } }
Notes:
- Flexibility: This example provides a basic structure. You can extend the DataTableConfig class with more configuration options (e.g., specifying which columns are sortable, adding custom classes for specific columns, etc.).
- Complex Columns: This example assumes each column is tied to a direct property on the data type. If you have more complex columns, adjustments would be needed.
Consider using View Components or integrating a dedicated front-end library for large, complex, or highly interactive tables.
By implementing custom HTML helpers for these use cases, developers can ensure consistency, reduce errors, and simplify the process of making global changes to the application’s views.
In the next article, I will discuss Creating Form Using HTML Helpers in ASP.NET Core MVC Applications with an Example. I explain Real-Time Examples of Custom HTML Helpers in ASP.NET Core MVC Applications with Examples in this article. I hope this Real-Time Examples of Custom HTML Helpers in ASP.NET Core MVC Applications article will help you with your needs.