How to Create Custom External Helper Methods in ASP.NET MVC

ASP.NET MVC

0 ( 0 votes) | 1886

In this article, we will talk about how to create and use external helper methods in an ASP.NET MVC application. In my post, How to Create Custom Inline Helper Methods in ASP.NET MVC  we talked about what are helper methods and how to create and use inline helper methods in MVC application. (Note: if you have not read the post regarding custom inline helper in MVC application, i will recommend reading it first as it is related to this post). Before getting started with how to create custom external helper methods, let`s just discuss about external helper method and when should we use it.

External Helper Method:

Helper methods are of two types, Inline helper methods and External helper methods. Inline helper methods are convenient, as they are declared in view and the complexity of the code is low. But if the code is becoming complex, then it will be difficult to read and understand the code in our view. The alternative for such situation is to create an external helper method. External helper methods are expressed as C# extension method. Now let`s get started with an example.

Getting Started:

We will use the same example that we used in my post How to Create Custom Inline Helper Methods in ASP.NET MVC of displaying the list of fruits and flowers (For simplicity purpose i am using the same example). Let`s recall our example. We have added the following code in index action of home controller.

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Fruits = new string[] {"Apple", "Mango", "Lemon"};
            ViewBag.Flowers = new string[] { "Rose", "Jasmine", "Sunflower" };
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }

The content of index view after using inline helper method is as shown below. 

@{
    ViewBag.Title = "Home Page";
}
 
@helper ListItems(string[] items)
{
    
    @foreach (var item in items) {
  • @item
  • }
}

Fruits

@ListItems(ViewBag.Fruits)

Flowers

@ListItems(ViewBag.Flowers)

We will use the same example project that we have created previously for inline helper. Now to display the list of fruits and flowers using custom external helper method, create a new folder called “Helpers” and add a new file called “ExternalHelper.cs” within it. Add the following code in that file.

namespace CustomInlineHelper.Helpers
{
    public static class ExternalHelper
    {
        public static MvcHtmlString ListItems(this HtmlHelper htmlHelper, string[] items)
        {
            var ulElement=new TagBuilder("ul");
            foreach (var item in items)
            {
                var liElement=new TagBuilder("li");
                liElement.SetInnerText(item);
                ulElement.InnerHtml += liElement.ToString();
            }
            return new MvcHtmlString(ulElement.ToString());
        }
    }
}

In the preceding code, we have created a custom external helper method called “ListItems“. It takes the array of string as a parameter and generates the HTML of ul element containing the li element for each string in the array.  It has two parameters, first one is HtmlHelper object and second one is an array of string. The first HtmlHelper object parameter with this keyword specifies that this is an extension method for HtmlHelper object.

In our helper method, we use the TagBuilder class to generate the HTML elements. This class is available in System.Web.Mvc namespace. In order to generate the HTML element, we need to create an instance of TagBuilder class and pass the name of the HTML element that we want to construct as a constructor parameter. For example, we can create the ul element using TagBuilder class as shown below.

var ulElement=new TagBuilder("ul");

Useful methods/properties of TagBuilder class:

  • AddCssClass (string) – Add Css class to the HTML Element.
  • GenerateId (string) – Use to generate id for the HTML element. The string parameter specifies the id for the Html element. This method replaces the periods in the id.

  • MergeAttribute (String, String, Boolean) – Use to add attribute to Html element. First parameter specifies the name of the attribute and second parameter specifies the value of attribute. Third Boolean parameter specifies if the same attribute already exists then should be replaced or not.SetInnerText (string) – Set the text content of the HTML element.SetInnerText (string) – Set the text content of the HTML element.
  • SetInnerText (string) – Set the text content of the HTML element.
  • InnerHtml – This property allows us to nest the HTML elements. (In our example, we have used this property to add the li element under the ul element.

The result of our helper method is MvcHtmlString object, the content of which are directly written to response. It takes Html markup that we have generated using TagBuilder class as a parameter and encode that string so that it is safe to display. Now let`s update the index view to use our external helper method. The content of updated index view is as shown below.

@using CustomInlineHelper.Helpers
@{
    ViewBag.Title = "Home Page";
}
 
 
 

Fruits

@GlobalHelper.ListItems(ViewBag.Fruits)

Flowers

@GlobalHelper.ListItems(ViewBag.Flowers)

Fruits

@Html.ListItems((string[])ViewBag.Fruits)

Flowers

@Html.ListItems((string[])ViewBag.Flowers)

There are two important points to note in preceding content of index view.

  • We need to add the namespace for the class containing our helper method at the top of the view to use the helper method ( In our case, namespace is CustomInlineHelper.Helpers)
  • We need to cast the ViewBag dynamic property parameter to the type we have defined in our external helper method. (In our case, type of parameter is an array of string)

There is an alternative solution for adding the namespace for our helper method. We can add that namespace in Views/web.config file. So that our helper method will always be available for use and we don`t need to add the using statement in each and every view. The content of Views/web.config file after adding the namespace is as shown below (F: 1)

Add namespace in Views/web.config file (F: 1)

I have updated the source code on my github repository, which we have used in my post How to Create Custom Inline Helper Methods in ASP.NET MVC to include these changes.

Conclusion:

We can encapsulate the complex code in an external helper method (extension method) and use it in multiple views. This also makes our view more simple and readable. We can also create a class library project and include these external helper methods in that project. So that next time if we need same functionality we just need to add the reference to our class library project. Hope this help you.

I hope you enjoyed reading the article.

Happy Coding!!!!!!

Manoj Kulkarni - Dotnetcontext

Manoj Kulkarni

I am programmer, passionate blogger and foodie. I live in Nashik. I am a .Net developer. I like to learn new technologies to keep my self-updated and share that knowledge with my blog readers, friends and colleague.

4 Comments


Kishor Jagtap - Dotnetcontext

Kishor JagtapMonday, June 22, 2015 11:24 AM

Very nice article manoj. I was looking for same. Thanks:)

Manoj Kulkarni - Dotnetcontext

Manoj KulkarniMonday, June 22, 2015 7:05 PM

Thank you for the feedback Kishor

Gaurav Raut - Dotnetcontext

Gaurav RautTuesday, June 23, 2015 9:02 AM

Thanks for the post it helped me a lot

Manoj Kulkarni - Dotnetcontext

Manoj KulkarniTuesday, June 23, 2015 7:51 PM

Thank you Gaurav for the feedback.

Add a new comment