Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Monday 13 June 2016

Inline and Custom Html Helpers in ASP.Net MVC

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 Helper in the previous article of this series.

In previous ASP.NET MVC Tutorials of this series, we saw:


Inline HTML Helpers:
@helper syntax is used for creating reusable Inline helper method. They make the code more reusable as well as more readable. Let’s see how to use them.

Create an empty ASP.Net MVC application.
Right click on the controller 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 Ordered List. We can reuse inline HTML helpers multiple time on the same View.
In order to access the same inline HTML Helper across the different view, we have to move our @helper methods in .cshtml files to 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 method for creating Custom HTML Helpers. We have added a class (named as 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 namespace reference and call that 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 method enables us to add new methods to an existing class. For creating an Extension method, we have to create a static class and 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 Image Custom helper method and extended the HtmlHelper class. Now go to view, add the namespace reference and call Image helper method from HTML Helper class.
Preview:

Now we can use Image Html Helper in all views. The only thing we have to do is add the reference at the top so that we can call/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 like it. Thanks!

0 comments:

Post a Comment

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook