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

ASP.NET MVC

0 ( 0 votes) | 2260

In this article, we will talk about what are helper methods, how to create and use helper methods in an ASP.NET Mvc application.

What are Helper methods?

Helpers are package of few lines of code or a markup which can be reused throughout an MVC application. There are two types of helper methods, Inline helper methods and External helper methods. In this article, we will talk about Inline helper methods.

Getting Started:

To get started, open Visual Studio 2013 and create a brand new ASP.NET MVC application.  Consider we need to display list of fruits and flowers. To do this let`s add the following code in Index action of HomeController.

using System.Web.Mvc;
 
namespace CustomInlineHelper.Controllers
{
    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();
        }
    }
}

As shown in above code, let`s display the data for fruits and flowers stored in ViewBag. Content of Index view is as shown below. 

@{
    ViewBag.Title = "Home Page";
}

Fruits

    @foreach (var item in (string[])ViewBag.Fruits) {
  • @item
  • }

Flowers

    @foreach (var item in (string[])ViewBag.Flowers) {
  • @item
  • }

Now let`s run the application (shortcut F5) to view the output. Output is as shown below (F: 1).

Output of the application (F: 1)

Now suppose instead of unordered list, we want to display the data as ordered list. Then in above case we need to make the change at two places in Index.cshtml file. This is where the inline helper methods come in play. We can encapsulate code (Combination of Html markup and razor code) in a helper method so that we can reuse in our application. We can create simple inline helper using @helper syntax.

Creating custom helper method using @helper syntax:

To create helper method, add the following code in index view of home controller.

@helper ListItems(string [] items)
{
    
    @foreach (var item in items) {
  • @item
  • }
}

Above code uses the @helper syntax to create a new inline helper called ListItems.  It looks like our normal C# method. It contain one parameter called items which a string array and body of the method is a combination of HTML markup and Razor Code. Just like our normal C# method it can contain any number of arguments (Arguments can be null able or optional argument). We can invoke this @helper method like our normal C# method as shown below.

@ListItems(ViewBag.Fruits)

Visual studio also provides the intellisense while invoking the method as shown below (F: 2).

Intellisense for helper methods in visual studio (F: 2)

Now let`s update the Index view to use the new helper method. Content for the updated index view 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)

Creating helper methods to use across multiple views:

In above case, we have declared the helper method in index view, so we will be able to use it in the same view. But there may be some situation where we may need to use the same functionality across multiple views. In that case, we need to declare the helper as a global method so that we can access it across multiple views. To make the helper method as global method, create a new file called “GlobalHelper.cshtml” in App_Code directory. We can name this file as we want. Now copy our ListItems helper method in “GlobalHelper.cshtml” file. The content of GlobalHelper.cshtml file is (F: 3):

Content of GlobalHelper.cshtml file (F: 3)

When we compile the code GlobalHelper.cshtml file will be compiled to a class with ListItems as its static method. We can invoke this global helper method like we invoke a static method of a class in c# as shown below.

@GlobalHelper.ListItems(ViewBag.Fruits)

Now let`s use this global helper in index view. Content of updated index view is:

@{
    ViewBag.Title = "Home Page";
}
 

Fruits

@GlobalHelper.ListItems(ViewBag.Fruits)

Flowers

@GlobalHelper.ListItems(ViewBag.Flowers)

Now we can use this helper in any view in our application. Source code for this example is available on my github repository.

Conclusion:

Using Razor @helper syntax we can encapsulate code (combination of Razor code and Html markup) in razor view which we can reuse across all the views in our application. So even if we need to change the code we just have to change at one place. This makes the code more readable and maintainable. 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.

Add a new comment