Back to: ASP.NET Core Tutorials For Beginners and Professionals
How to Create Custom HTML Helper in the ASP.NET Core MVC?
In this article, I will discuss How to Create Custom HTML Helpers in ASP.NET Core MVC Applications with Examples. Please read our previous article discussing Hidden Field HTML Helper in ASP.NET Core MVC. As part of this article, we will discuss the following two important pointers.
- How can we Display Images in an ASP.NET Core MVC Application?
- How do we Create Custom HTML Helpers in ASP.NET Core MVC to display Images?
The ASP.NET Core MVC Framework provides many built-in HTML helper methods that we can directly use in a Razor View. The ASP.NET Core MVC Framework also allows the creation of a Custom HTML Helper Method. Once you create the custom HTML helper method, you can reuse it many times in your application.
Example to Understand Custom HTML Helpers in ASP.NET Core MVC:
In this demo, we will display the employee details and the Employee photo, as shown in the image below.
Creating Employee Model:
First, create one class file with the name Employee.cs within the Models Folder and then copy and paste the following code into it.
namespace HTML_HELPER.Models { public partial class Employee { public int Id { get; set; } public string? FullName { get; set; } public string? Designation { get; set; } public string? Department { get; set; } public string? Photo { get; set; } public string? AlternateText { get; set; } } }
Creating Images Folder within the wwwroot Folder:
Next, add a folder with the Name Images within the wwwroot Folder. To do so, Right-click on the wwwroot, select Add Folder, and then rename the folder as Images. Then download and add the following image to the Images Folder. Rename the image name as MyPhoto.png.
Modifying Home Controller:
Next, modify the Home Controller as follows.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class HomeController : Controller { public ActionResult Index() { //Here we hardcoded the Employee Details //In Realtime, you will get the data from any data source Employee employee = new Employee() { Id = 106724, FullName = "Pranaya Rout", Designation = "Manager", Department = "IT", Photo = "/Images/MyPhoto.png", AlternateText = "Pranaya Rout Photo Not Available" }; return View(employee); } } }
Modifying the Index.cshtml view file of Home Controller:
Next, open the Index.cshtml view file and then copy and paste the following code into it.
@model HTML_HELPER.Models.Employee @{ ViewBag.Title = "Employee Details"; } <div> <h4>Employee Details</h4> <hr /> <p> Employee ID: @Html.DisplayFor(model => model.Id) </p> <p> Full Name: @Html.DisplayFor(model => model.FullName) </p> <p> Designation: @Html.DisplayFor(model => model.Designation) </p> <p> Department: @Html.DisplayFor(model => model.Department) </p> <p> Photo: @Html.DisplayFor(model => model.Photo) </p> <p> AlternateText: @Html.DisplayFor(model => model.AlternateText) </p> </div>
Now, Run the application and navigate to the URL Home/Index. It will produce the following output. Notice that the Photo and AlternateText property values are displayed instead of rendering the photo.
To display the image, modify the Index.cshtml file as follows:
@model HTML_HELPER.Models.Employee @{ ViewBag.Title = "Employee Details"; } <div> <h4>Employee Details</h4> <hr /> <p> Employee ID: @Html.DisplayFor(model => model.Id) </p> <p> Full Name: @Html.DisplayFor(model => model.FullName) </p> <p> Designation: @Html.DisplayFor(model => model.Designation) </p> <p> Department: @Html.DisplayFor(model => model.Department) </p> <p> Photo: <img src="@Model.Photo" alt="@Model.AlternateText" height="200" width="200" /> </p> </div>
Notice that here, we are using an image HTML tag. Now, run the application and notice that the image is displayed as expected, as shown in the image below.
We use the below code to render Images in the ASP.NET MVC application. We are building the image tag by passing the values for the src and alt attributes.
<img src=”@Model.Photo” alt=”@Model.AlternateText”/>
Though the above code is not very complex, moving this logic into its own helper method still makes sense. We don’t want any complicated logic in our views. Views should be as simple as possible. Don’t you think it would be very nice if we could render the image using the Image() HTML helper method as shown below?
@Html.Image(Model.Photo, Model.AlternateText)
But, ASP.NET Core MVC does not provide any built-in Image() HTML helper. So, let’s build our own custom image HTML helper method.
Custom Image HTML Helper in ASP.NET Core MVC
In ASP.NET Core MVC, we can create a custom HTML Helper method to generate a <img> tag with additional attributes or behavior. The Custom HTML Helper methods allow us to encapsulate reusable HTML generation logic in our application. Let us proceed and understand How We Can Create a Custom Image HTML Helper Method in ASP.NET Core MVC.
Create a Helper Method:
So, we need to create a static method that generates the desired HTML markup for the custom Image tag. This method should typically reside in a class marked as public static. The first parameter of the static method should be this IHtmlHelper helper. So, create a class file with the name CustomHTMLHelper.cs (you can give any name) within the Models folder (You can create inside any folder or directory) and then copy and paste the following code into it.
using Microsoft.AspNetCore.Mvc.Rendering; namespace HTML_HELPER.Models { public static class CustomHTMLHelper { public static TagBuilder Image(this IHtmlHelper helper, string src, string alt, string height, string width, string cssClass) { var imgTag = new TagBuilder("img"); imgTag.MergeAttribute("src", src); if (alt != null) { imgTag.MergeAttribute("alt", alt); } if (Convert.ToInt32(height) > 0) { imgTag.MergeAttribute("height", height); } if (Convert.ToInt32(height) > 0) { imgTag.MergeAttribute("width", width); } if (cssClass != null) { //imgTag.MergeAttribute("class", cssClass); imgTag.AddCssClass(cssClass); } return imgTag; } } }
Use the Custom HTML Helper:
In your Razor view, you can use the custom HTML Helper to generate the custom image tag by calling the Image Helper method. So, modify the Index.cshtml file as shown below. In the below example, the Image Custom HTML Helper method generates a <img> tag with the specified src, alt, width, height, and CSS class.
@model HTML_HELPER.Models.Employee @{ ViewBag.Title = "Employee Details"; } <div> <h4>Employee Details</h4> <hr /> <p> Employee ID: @Html.DisplayFor(model => model.Id) </p> <p> Full Name: @Html.DisplayFor(model => model.FullName) </p> <p> Designation: @Html.DisplayFor(model => model.Designation) </p> <p> Department: @Html.DisplayFor(model => model.Department) </p> <p> Photo: @Html.Image(Model.Photo, Model.AlternateText, "150", "150", null ) </p> </div>
With the above changes in place, run the application, and you will get the output as expected, as shown in the image below.
Custom HTML Helpers provide a convenient way to encapsulate complex HTML generation logic, making your views cleaner and more maintainable. They can be especially useful when generating custom HTML elements that require specific attributes or behaviors.
Another Way to Use Custom HTML Helper Method:
Now, instead of creating the Image method as an extension method, we can also create this as a non-extension method and use it inside our views. For example, modify the CustomHTMLHelper class as follows:
using Microsoft.AspNetCore.Mvc.Rendering; namespace HTML_HELPER.Models { public static class CustomHTMLHelper { public static TagBuilder Image(string src, string alt, string height, string width, string cssClass) { var imgTag = new TagBuilder("img"); imgTag.MergeAttribute("src", src); if (alt != null) { imgTag.MergeAttribute("alt", alt); } if (Convert.ToInt32(height) > 0) { imgTag.MergeAttribute("height", height); } if (Convert.ToInt32(height) > 0) { imgTag.MergeAttribute("width", width); } if (cssClass != null) { //imgTag.MergeAttribute("class", cssClass); imgTag.AddCssClass(cssClass); } return imgTag; } } }
The above Image method is not an extension method, so we cannot invoke this method using the @Html property. Instead, we can call this method using the class name, i.e., CustomHTMLHelper. So, modify the Index.cshtml file as follows.
@model HTML_HELPER.Models.Employee @{ ViewBag.Title = "Employee Details"; } <div> <h4>Employee Details</h4> <hr /> <p> Employee ID: @Html.DisplayFor(model => model.Id) </p> <p> Full Name: @Html.DisplayFor(model => model.FullName) </p> <p> Designation: @Html.DisplayFor(model => model.Designation) </p> <p> Department: @Html.DisplayFor(model => model.Department) </p> <p> Photo: @CustomHTMLHelper.Image(Model.Photo, Model.AlternateText, "150", "150", null ) </p> </div>
Now, run the application, and you should get the same output.
When to Use Custom HTML Helper in ASP.NET Core MVC?
Custom HTML Helpers in ASP.NET Core MVC are useful for encapsulating complex or repetitive HTML generation logic into reusable functions. They enhance the maintainability and readability of your views by abstracting away intricate HTML markup. Here are some scenarios where using a Custom HTML Helper can be beneficial:
- Custom Controls: When creating custom controls or components involving complex HTML structures or client-side scripting, a Custom HTML Helper can make the code more manageable and reusable.
- Consistent UI Elements: If you have UI elements that need consistent styling and behavior across multiple views, a Custom HTML Helper can ensure that these elements are generated consistently.
- Generating Complex Markup: A Custom HTML Helper can simplify the process when you need to generate HTML markup that’s difficult to manage directly within Razor syntax, such as tables with dynamic row and column structures.
- Logic-Heavy Markup: If your HTML markup requires conditional logic, loops, or calculations, a Custom HTML Helper can encapsulate this logic, making your views cleaner and easier to understand.
- Reusable Components: When building modular applications, you might want to encapsulate certain UI components or widgets as Custom HTML Helpers. This promotes reusability and modularity.
- Domain-Specific Formatting: If you have specific formatting needs based on your domain (e.g., formatting dates, numbers, or other data), a Custom HTML Helper can handle this formatting consistently across your application.
- Third-Party Integrations: When integrating third-party libraries or widgets that require specific HTML and script setup, a Custom HTML Helper can encapsulate the integration logic, making it easier to manage.
- Security and Validation: A Custom HTML Helper can centralize these concerns if you need to include additional security features or validation checks in your HTML generation.
- Separation of Concerns: Using a Custom HTML Helper can help separate the concerns of your view code, making it more focused on presenting data rather than generating complex markup.
- Improving Readability: If your Razor views are cluttered with complex or repeated HTML, a Custom HTML Helper can make your views more readable and maintainable.
Remember that while Custom HTML Helpers can be powerful, they should be used judiciously. Overusing them for simple tasks might introduce unnecessary complexity. Also, ensure that your Custom HTML Helpers have clear and concise names, follow good coding practices, and provide proper documentation when used in a team environment.
In the next article, I will discuss Real-Time Examples of Custom HTML Helpers in ASP.NET Core MVC Applications with Examples. In this article, I explain How to Create a Custom Image HTML Helper in ASP.NET Core MVC Application with Examples. I hope this How to Create Custom Image HTML Helper in ASP.NET Core MVC article will help you with your needs.