Custom HTML Helpers in MVC

Creating Custom HTML Helpers in MVC application

In this article, I am going to discuss how to create Custom HTML Helpers in MVC application. 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 ASP.NET MVC framework also provides us with the facility to create our Custom HTML Helpers in MVC application. Once you create your custom HTML helper method then you can reuse it many times.  As part of this article, we are going to discuss the following two things 

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

How to create Custom HTML Helpers in MVC to display images?

Let’s understand Custom HTML Helpers in MVC with an example.

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

Creating Custom HTML Helpers in MVC application

First, create an empty ASP.NET MVC application with the name CustomHTMLHelperThen create one model class with the name Employee within the Models Folder and then copy and paste the following code in 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 and select Add Folder and then rename the folder as “Photos“. Then download and add the following image within the Photos Folder. Rename the image name as MyPhoto.png.Custom HTML Helpers in ASP.NET MVC  
Now add a controller with the name EmployeeController within the Controllers folder and then copy and paste the below codes.

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);
        }
    }
}
Next, add the Details view and then copy and paste the following codes in it.
@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 navigates to the below URL.

http://localhost:61629/Employee/Details

It will produce the below output.

Creating Custom HTML Helpers in MVC application

Notice that in the above image, instead of rendering the photo, the PhotoPath and AlternateText property values are displayed.

Let’s see how to display image in MVC.
<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 below image.

Custom HTML Helpers in ASP.NET MVC

We use the below code to render Image in ASP.NET MVC application. We are building the image tag, bypassing the values for “src” and “alt” attributes.

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

Though the above code is not very complex, it still makes sense to move this logic into its own helper method. 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 can render the image, using Image() HTML helper method as shown below.

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

But, 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 simply returns a string. To generate a textbox, we use the following code in our view.

@Html.TextBox(“TextBox Name”)

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

Let’s now add, Image() extension method, to HtmlHelper class. 

Right-click on the project and add “CustomHelpers” folder.  Then Right click on “CustomHelpers” folder and add “CustomHelpers.cs” class file. Copy and paste the following code in it. The code is commented and self-explanatory. TagBuilder class is in 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 statement in Details.cshtml

@using CustomHTMLHelper.CustomHelpers;

As we intend to use this Image() HTML helper, in all our views, let’s include “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, then, include a web.config file in the specific views folder, and then specify the namespace in it. 

In the next article, I will discuss Attributes in ASP.NET MVC.

SUMMARY:

In this article, I try to explain how to create Custom HTML Helpers in MVC application. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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