Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Inline and Custom HTML Helpers in ASP.NET MVC

DZone's Guide to

Inline and Custom HTML Helpers in ASP.NET MVC

How to use inline and custom HTML helpers to create programmatic HTML controls in ASP.NET MVC.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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:

Image title

Right click on the controller button and add a controller.

Image title

public class HomeController : Controller
{

    public ActionResult InlineHTMLHelper()
    {
        return View();
    }
}

Right click on Action Method and click on Add View.

Image title

@{
    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:

Image title

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.

Image title

@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:

Image title

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.

Image title

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:

Image title

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.

Image title

Preview:

Image title

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!

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
asp.net mvc ,asp.net ,.net ,html ,web dev

Published at DZone with permission of Anoop Kumar Sharma, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}