Custom HTML Helper in ASP.NET Core MVC 

Custom HTML Helper in the ASP.NET Core MVC?

In this article, I will discuss How We 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.

  1. How can we Display Images in an ASP.NET Core MVC Application?
  2. 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.

Example to Understand Custom HTML Helpers in ASP.NET Core MVC

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.

Creating Images Folder within the wwwroot Folder

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.

How to Create Custom Image HTML Helpers in ASP.NET Core MVC Applications with Examples

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 we are using an image HTML tag here. Now, run the application and notice that the image is displayed as expected, as shown in the image below.

How to Create Custom Image HTML Helpers in ASP.NET Core MVC

We use the code below 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 HTML Helper in ASP.NET Core MVC

Custom HTML helpers are user-defined methods that extend the functionality of built-in HTML helpers or provide new functionality altogether. They allow developers to encapsulate common HTML markup patterns or generate complex HTML structures and reuse them across multiple views.

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:

To create a custom HTML helper in ASP.NET Core MVC, we need to follow the below steps:

  • Create a Helper Class: Start by creating a static class to contain your custom HTML helper methods. 
  • Create Extension Methods: Define extension methods within your helper class. These methods should extend the IHtmlHelper interface or any derived interface, allowing you to access HTML generation methods.
  • Implement Helper Methods: Write the logic for your custom HTML helper methods within the extension methods. These methods should generate HTML markup based on the provided parameters.
  • Register the Helper Class: Register your custom HTML helper class with the MVC framework during application startup. This step ensures that your helper methods are available for use throughout your application.

So, create a class file named CustomHTMLHelper.cs (you can give it any name) within the Models folder (you can create it 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(width) > 0)
            {
                imgTag.MergeAttribute("width", width);
            }

            if (cssClass != null)
            {
                //imgTag.MergeAttribute("class", cssClass);
                imgTag.AddCssClass(cssClass);
            }

            return imgTag;
        }
    }
}
Explanation of the above class:

The above class defines a CustomHTMLHelper class in C# that extends the capabilities of ASP.NET’s IHtmlHelper interface, specifically for generating HTML image tags. The Image method is an extension method for IHtmlHelper, enabling the dynamic creation of <img> HTML elements with specified attributes. Here’s a breakdown of its functionality:

Class Definition (public static class CustomHTMLHelper): The class is declared public and static, meaning it is accessible globally and cannot be instantiated. It’s meant to contain static methods only, without any instance members.

Extension Method (public static TagBuilder Image(this IHtmlHelper helper, …)): This method is an extension method, as indicated by the “this” keyword in its first parameter. It allows the method to be called on any object of type IHtmlHelper, effectively extending that interface with new functionality. This is useful for adding methods to an interface without modifying its original definition.

Parameters: The method takes several parameters for constructing an image tag:

  • src (string): The URL of the image to be displayed.
  • alt (string): The alternative text for the image, which is displayed when the image cannot be loaded.
  • height (string) and width (string): Dimensions for the image. These are set as attributes only if their converted integer value is greater than 0, which is a basic validation to ensure that dimensions are positive.
  • cssClass (string): An optional CSS class to be applied to the image tag for styling.

TagBuilder Usage: TagBuilder is a utility class for building HTML tags in a structured way. The code creates a new TagBuilder instance for an <img> tag and sets its attributes based on the method’s parameters.

Conditional Attributes: The method checks if certain parameters (alt, height, width, and cssClass) are provided and valid before adding them as attributes to the <img> tag. For example, it only adds the height and width attributes if their values can be converted to integers greater than 0. This prevents the generation of invalid HTML.

CSS Class Application: Instead of directly merging the class attribute, the code uses AddCssClass for the cssClass parameter, which is a more appropriate method for adding CSS classes as it handles the class attribute’s unique behavior in HTML (e.g., appending to existing classes).

Return Value: The method returns the constructed TagBuilder object representing the <img> tag, which can then be rendered to HTML.

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>

After making the above changes, run the application, and you will get the output as expected, as shown in the image below.

How to Create Custom HTML Helper in ASP.NET Core

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(width) > 0)
            {
                imgTag.MergeAttribute("width", width);
            }

            if (cssClass != null)
            {
                //imgTag.MergeAttribute("class", cssClass);
                imgTag.AddCssClass(cssClass);
            }

            return imgTag;
        }
    }
}
Explanation of the above Code:

The above code defines a static class called CustomHTMLHelper with a static method Image that generates an HTML img tag with specified attributes. Here’s a breakdown of the method:

Parameters:

  • src: The URL of the image.
  • alt: The alternate text for the image.
  • height: The height of the image.
  • width: The width of the image.
  • cssClass: The CSS class for the image.

Creating TagBuilder: TagBuilder is a class used to generate HTML tags programmatically. In this code, a new TagBuilder object for the img tag is created.

Setting Attributes: The mergeAttribute method sets attributes like src, alt, height, and width of the img tag based on the parameters provided.

  • The src attribute is always set.
  • The alt attribute is set only if a non-null value is provided.
  • The height and width attributes are set only if their corresponding parameters are greater than 0.

Adding CSS Class: The cssClass parameter is added as a CSS class to the img tag using the AddCssClass method.

Returning TagBuilder: Finally, the method returns the TagBuilder object representing the img tag with the specified attributes.

This method provides a convenient way to generate HTML img tags with specified attributes in a structured manner. It abstracts away the complexity of manually creating and setting attributes for the img tag, making the code more readable and maintainable. 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 Should We Use Custom HTML Helper in ASP.NET Core MVC?

Here are some scenarios where using custom HTML Helpers can be advantageous:

  • Reusable UI Components: If you have UI components that are reused across multiple views or even multiple projects, creating custom HTML Helpers can help encapsulate the HTML generation logic, promoting code reusability and maintainability.
  • Complex Markup Generation: When you need to generate complex HTML markup involving multiple elements or conditional logic, custom HTML Helpers can provide a cleaner and more maintainable way to generate such markup than embedding the HTML directly within the Razor view.
  • Consistent Output and Centralized Updates: By centralizing the HTML generation logic within custom HTML Helpers, you ensure consistency in the generated output across your application. Additionally, any updates or modifications to the markup can be made in a centralized location, simplifying maintenance and reducing the risk of inconsistencies.

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 article on creating a custom image HTML helper in ASP.NET Core MVC will help you with your needs.

Leave a Reply

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