Custom HTML Helpers in ASP.NET MVC

Creating Custom HTML Helpers in ASP.NET MVC Application

In this article, I am going to discuss How to Create Custom HTML Helpers in ASP.NET MVC Applications with Examples. Please read our previous article, where we discussed how to Customizing Template Helpers in ASP.NET MVC application. As part of this article, we are going to discuss the following two things. 

  1. How can we Display Images in an ASP.NET MVC application?
  2. How do we create Custom HTML Helpers in MVC to display images?

As we already discussed, the HTML helper is a method that returns an HTML string. Then, this HTML string is rendered in a view. ASP.NET MVC provides many built-in HTML helper methods that we can directly use in a view. The MVC framework also allows the creation of Custom HTML Helpers in ASP.NET MVC applications. Once you create your custom HTML helper method, you can reuse it many times. 

Understanding Custom HTML Helpers in MVC:

In this demo, we will display the employee details along with the Employee photo, as shown in the image below. 

Creating Custom HTML Helpers in ASP.NET MVC application

Creating an empty ASP.NET MVC application

First, create an empty ASP.NET MVC application with the name CustomHTMLHelper. Then, create one model class with the name Employee within the Models Folder and copy and paste the following code into it.

namespace CustomHTMLHelper.Models
{
    public partial class Employee
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public string Gender { get; set; }    
        public string EmailAddress { get; set; }
        public string PersonalWebSite { get; set; }
        public string Photo { get; set; }
        public string AlternateText { get; set; }
    }
}

Then, add a folder with the Name Photos to the project.

To do this, Right-click on the Project, select Add Folder, and then rename the folder as “Photos“. Then download and add the following image to the Photos Folder. Rename the image name as MyPhoto.png.

Custom HTML Helpers in ASP.NET MVC

Creating Controller:  

Now add a controller named EmployeeController within the Controllers folder and then copy and paste the codes below.

namespace CustomHTMLHelper.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Details()
        {
            //Here we are hardcoded the Employee Details
            //In Realtime you will get the data from any data source
            Employee employee = new Employee()
            {
                Id = 1,
                FullName = "Pranaya Rout",
                Gender = "Male",
                EmailAddress = "info@dotnettutorials.com",
                PersonalWebSite = "https://dotnettutorials.net/",
                Photo = "~/Photos/MyPhoto.png",
                AlternateText = "Pranaya Rout Photo not available"
            };
            return View(employee);
        }
    }
}
Adding View:

Add the Details view and copy and paste the following codes.

@model CustomHTMLHelper.Models.Employee
@{
    ViewBag.Title = "Details";
}

<div>
    <h4>Employee Details</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.FullName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.FullName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Gender)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Gender)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.EmailAddress)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmailAddress)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.PersonalWebSite)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.PersonalWebSite)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Photo)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Photo)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.AlternateText)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.AlternateText)
        </dd>

    </dl>
</div>

Now, Run the application and navigate to the URL http://localhost:61629/Employee/Details. It will produce the following output.

How we can display Images in an ASP.NET MVC application

Notice that the PhotoPath and AlternateText property values are displayed instead of rendering the photo.

How to display an image in ASP.NET MVC Application?
<dt>
    @Html.DisplayNameFor(model => model.Photo)
</dt>

<dd>
    @Html.DisplayFor(model => model.Photo)
</dd>

<dt>
    @Html.DisplayNameFor(model => model.AlternateText)
</dt>

<dd>
    @Html.DisplayFor(model => model.AlternateText)
</dd>
Replace the above code with the following code.
<dt>
    @Html.DisplayNameFor(model => model.Photo)
</dt>

<dd>
    <img src="@Url.Content(@Model.Photo)" alt="@Model.AlternateText" />
</dd>

Notice that now, we are using the Url.Content() HTML helper method. This method resolves a URL for a resource when we pass it the relative path. Now, run the application and notice that the image is displayed as expected, as shown in the image below.

Custom HTML Helpers in MVC application

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=”@Url.Content(@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 MVC does not provide any built-in Image() HTML helper. So, let’s build our own custom image HTML helper method. Let’s take a step back and understand HTML helper methods. The HTML helper method returns a string. To generate a textbox, we use the following code in our view.

@Html.TextBox(“TextBox Name”)

So, TextBox() is an extension method defined in the HtmlHelper class. In the above code, HTML is the property of the View, which returns an instance of the HTML helper class.

Creating Image() Extension Method to HtmlHelper class. 

Right-click on the project and add the “CustomHelpers” folder.  Then Right-click on the “CustomHelpers” folder and add the “CustomHelpers.cs” class file. Please copy and paste the following code into it. The code is commented and self-explanatory. TagBuilder class is in the System.Web.Mvc namespace.

using System.Web;
using System.Web.Mvc;

namespace CustomHTMLHelper.CustomHelpers
{
    public static class CustomHelpers
    {
        public static IHtmlString Image(this HtmlHelper helper, string src, string alt)
        {
            // Build <img> tag. The parameter name must be img 
            TagBuilder tb = new TagBuilder("img");
            // Add "src" attribute
            tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
            // Add "alt" attribute
            tb.Attributes.Add("alt", alt);
            // return MvcHtmlString. This class implements IHtmlString
            // interface. IHtmlStrings will not be html encoded.
            return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
        }
    }
}

To use the custom Image() HTML helper in Details.cshtml view, please include the following using the statement in Details.cshtml

@using CustomHTMLHelper.CustomHelpers;

As we intend to use this Image() HTML helper in all our views, let’s include the “CustomHTMLHelper.CustomHelpers” namespace in web.config that is present in the Views Folder. This eliminates the need to include the namespace in each and every view.

<system.web.webPages.razor>
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <add namespace="TemplateHelpersMVC" />
   <add namespace="CustomHTMLHelper.CustomHelpers" />
    </namespaces>
  </pages>
  <host ....../>
</system.web.webPages.razor>

Now, use the following code to display an Image.

@Html.Image(Model.Photo, Model.AlternateText)

If you intend to use the Image() custom HTML helper only with a set of views, include a web.config file in the specific views folder and then specify the namespace in it. 

In the next article, I am going to discuss Attributes in ASP.NET MVC. I explain how to create Custom HTML Helpers in an MVC application in this article. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, questions, or comments about this article.

Leave a Reply

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