Inline and Custom HTML Helpers in ASP.Net MVC

Datetime:2016-08-23 04:39:02          Topic: HTML  ASP.NET MVC           Share

With the help of HTML Helper class, we can create HTML Controls programmatically. HTML Helpers are used in View to render HTML content. HTML Helpers (Mostly), is a method that returns a string.

HTML Helpers are categorized into three types:

1. Inline HTML Helpers

2. Built-in HTML Helpers

3. Custom HTML Helpers

In this article, we will learn how to create inline and custom HTML Helpers. We have already covered Built-in HTML Helpers in the previous article of this series.

In my previous ASP.NET MVC tutorials, we've seen:

Inline HTML Helpers

@helper syntax is used for creating reusable inline helper methods. They make the code more reusable as well as more readable. Let’s look at how to use them.

Create an empty ASP.Net MVC application:

Right click on the controller button and add a controller.

public class HomeController : Controller
{
       
    public ActionResult InlineHTMLHelper()
    {
        return View();
    }
}

Right click on Action Method and click on Add View.

@{
    Layout = null;
}

@helper OrderedList(string[] words)
{
    <ol>
        @foreach(string word in words)
        {
            <li>@word</li>
        }
    </ol>
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Inline HTML Helper</title>
</head>
<body>
    <div>
        @OrderedList(new string[]{"Delhi","Punjab","Assam","Bihar"})

    </div>
</body>
</html>

Preview:

In the above code, we have created an inline helper method (i.e. OrderedList) which takes a string array as an argument and displays each word in an ordered list. We can reuse inline HTML helpers multiple times in the same View.

In order to access the same inline HTML Helpers across the different views, we have to move our @helper methods in .cshtml files to the App_Code folder.

@helper OrderedList(string[] words)
{
    <ol>
        @foreach (string word in words)
        {
            <li>@word</li>
        }
    </ol>
}
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Inline HTML Helper App Code</title>
</head>
<body>
    <div>
        @InlineHelplerCode.OrderedList(new string[] { "Delhi", "Punjab", "Assam", "Bihar" })
    </div>
</body>
</html>

Preview:

Custom HTML Helpers

We can create Custom HTML Helpers in two ways:

  1. Using Static methods.

  2. Using Extension methods.

Using Static Methods

This is one of the simplest methods for creating custom HTML helpers. We have added a class (named CustomHelper) in CustomHelper folder.

public static class CustomHelper
{
        public static MvcHtmlString Image(string source,string altTxt,string width,string height){
            //TagBuilder creates a new tag with the tag name specified
            var ImageTag = new TagBuilder("img");
            //MergeAttribute Adds attribute to the tag
            ImageTag.MergeAttribute("src", source);
            ImageTag.MergeAttribute("alt", altTxt);
            ImageTag.MergeAttribute("width", width);
            ImageTag.MergeAttribute("height", height);
            //Return an HTML encoded string with SelfClosing TagRenderMode
            return MvcHtmlString.Create(ImageTag.ToString(TagRenderMode.SelfClosing));
        }

}

In the above code we have created a static method that returns an HTML-encoded string using MvcHtmlString. Now add some namespace references and call Custom Helper from the view.

@{
    Layout = null;
}
@using InlineAndCustomHTMLHelper.CustomHelper
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Custom Static HTML Helper</title>
</head>
<body>
    <div>
        @CustomHelper.Image("/Images/UserPic.jpg","UserPic","100","100")
    </div>
</body>
</html>

Preview:

Using Extension Methods

Extension methods enable us to add new methods to an existing class. To create an extension method, we have to create a static class, and the first parameter of an extension method points towards the class that is extended by the method.

public static MvcHtmlString Image(this HtmlHelper htmlhelper, string source, string altTxt, string width, string height)
{
            var ImageTag = new TagBuilder("img");
            ImageTag.MergeAttribute("src", source);
            ImageTag.MergeAttribute("alt", altTxt);
            ImageTag.MergeAttribute("width", width);
            ImageTag.MergeAttribute("height", height);
            return MvcHtmlString.Create(ImageTag.ToString(TagRenderMode.SelfClosing));
}

In the above code, we have added teh image custom helper method and extended the HtmlHelper class. Now go to view, add the namespace reference, and call the image helper method from the HTML Helper class.

Preview:

Now we can use the image HTML helper in all views. The only thing we have to do left is to add the reference at the top so that we can call or invoke that custom helper method. If you want to use that custom helper method multiple times, you can add namespace of that custom helper class in the view’s web.config file.

<add namespace="InlineAndCustomHTMLHelper.CustomHelper"/>

I hope you liked this. Thanks!





About List