Working with Helper methods in MVC Application


In this article we are going to focus on Helper methods in an MVC Application. We will look at the following topics :
1. Creating Custom Helper Methods
2. About Built-in Helper Methods
3. About Strongly Typed Input Helpers


In this article we are going to focus on Helper methods in an MVC Application. We will look at the following topics :

1. Creating Custom Helper Methods
2. About Built-in Helper Methods
3. About Strongly Typed Input Helpers

Why Helper methods
It allows us to wrap up chunks of code and markup so that it can be reused anywhere in an MVC Framework application.
The MVC framework provides many built-in helper methods.
We can use Helper methods to create HTML form, select and input elements.
Helper Methods are trusted to generate safe content that is the reason we can use html elements such as <b> or <p> in the helper methods.

Here I am going to illustrate HTML Helper methods by creating a MVC Application.

Step 1
Create a new Visual Studio MVC project called HelperMethodsDemo using the Basic
template option.

Step 2
Right click the controllers folder in the Solution Explorer and Add controller called HomeController.

Step 3
Add the below code to the HomeController class


public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.IceCreamFlavor = new string[] { "Vanilla", "Butterscotch", "Chocolate" };
ViewBag.IceCreamType = new string[] { "Cup", "CakeCone", "Gelato" };
string message = "This is an HTML element";
return View((object)message);
}
}

In the above code we are passing a pair of string arrays to the view using the view bag feature and we have also set the model object to be a string with the name message.
Step 4
Add a New folder called "Home" to the Views folder. Right Click the Home Folder and add a New View
Right-click the Index method and choose Add View -> Name it as Index. Uncheck the options "use a layout or master page" and click on Add. This adds a Index.cshtml View in the Home folder inside the Views folder.
Step 5
Add the below code in the Index.cshtml file

@model string
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Ice Cream</title>
</head>
<body>
<div>
Ice Cream Flavors:
@foreach (string str in (string[])ViewBag.IceCreamFlavor)
{
<b>@str </b>
}
</div>
<div>
Ice Cream Types:
@foreach (string str in (string[])ViewBag.IceCreamType)
{
<b>@str </b>
}
</div>
<div>
My message:
<p>@Model</p>
</div>
</body>
</html>

Step 6
Start the application and see how the View is displayed. the default routing
configuration added to the MVC project in the ..\App_Start\RouteConfig.cs file by Visual Studio will map the root URL requested automatically by the browser to the Index action on the Home controller

Creating Custom Helper Methods
There are two ways of creating Custom Helper Methods :

First method: Creating an Inline Helper Method
1. It is very simple
2. It can be defined within the View and it has same syntax as the Razor view. Literal strings are considered as static HTML whereas the statements that require processing by Razor are prefixed with the @ character.
3. It evaluates types at run time
4. We can create an inline helper using the @helper tag as shown in the below code.
5. They have names and parameters just like our C# methods.
6. In the below example, we defined a helper called DisplayArrayItems, which takes a string array as a parameter.
7. It does not return any value.
8. The contents of the inline helper body are processed and sent into the response to the client.
9. The advantage of this technique is that it reduces the amount of duplicate
code and markup and we have to make only one change if we would like to change the way our array items are rendered.

@model string
@{
Layout = null;
}

@helper DisplayArrayItems(String[] data)
{
foreach(String str in data)
{
<br />
<b>@str</b>
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Ice Cream</title>
</head>
<body>
<div>
Ice Cream Flavors:
@DisplayArrayItems(ViewBag.IceCreamFlavor)
</div>
<div>
Ice Cream Types:
@DisplayArrayItems(ViewBag.IceCreamType)
</div>
<div>
My message:
<p>@Model</p>
</div>
</body>
</html>


Disadvantages of using inline Helper methods are:
1. They can be used only from within the view in which they are declared.
2. If it contains more code then it makes the view less readable.

An alternative to inline helper methods is External Helper Methods which is our next topic.

Second method: Creating an External Helper Method
1. It is expressed as a C# extension method.
2. It can be used extensively but it is little tough to write as C# does not naturally handle HTML element generation gracefully.

Let us see an example of how to create a External Helper method:
1. Create an Infrastructure folder in our MVC project
2. Create a new class file called "CustomHelpers.cs" in the Infrastructure folder.
3. Write the below code in the CustomHelper class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HelperMethodsDemo.Infrastructure
{
public static class CustomHelpers
{
public static MvcHtmlString DisplayArrayItems(this HtmlHelper html, string[] lstData)
{
TagBuilder tag = new TagBuilder("ul");
foreach (string str in lstData)
{
TagBuilder tagBuilder = new TagBuilder("li");
tagBuilder.SetInnerText(str);
tag.InnerHtml += tagBuilder.ToString();
}
//Generate the HTML fragment that contains the ul and li elements and return them
to the razor viewengine so that it can be written into the response.
return new MvcHtmlString(tag.ToString());
}
}
}

4. The above helper method takes an array of strings as input and generates an HTML ul element, which in turn contains a li element for each string in the array.
5. The first parameter to the DisplayArrayItems helper method is an HtmlHelper object, prefixed with the this keyword. It tells the C# compiler that we are defining an extension method.
6. Here we are creating HTML in the helper method by using the TagBuilder class, which allows us to build up HTML strings without worrying about the escaping and special characters.
7. Here we are creating a new TagBuilder instance, by passing in the name of the HTML element we want to construct as the constructor parameter.
8. The result of an DisplayArrayItems helper method is an MvcHtmlString object, the contents of which are sent directly into the response to the client.

Next we will see how to use the Custom External Helper method in our Index.cshtml view.

Write the below code in the Index.cshtml file:

@model string
@using HelperMethodsDemo.Infrastructure @*Add the namespace that contains the helper extension method*@

@{
Layout = null;
}

@helper DisplayArrayItems(String[] data)
{
foreach (String str in data)
{<br />
<b>@str</b>
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Ice Cream</title>
</head>
<body>
<div>
Ice Cream Flavors:
@Html.DisplayArrayItems((String[])ViewBag.IceCreamFlavor)
</div>
<div>
Ice Cream Types:
@Html.DisplayArrayItems((String[])ViewBag.IceCreamType)
</div>
<div>
My message:
<p>@Model</p>
</div>
</body>
</html>


Please note the below points in the above code:

1. Here we are referring to the helper using @Html.<helper>, where <helper> is the name of our extension method (DisplayArrayItems)
2. The Html part of this expression: @Html.DisplayArrayItems refers to a property which is defined by the view base class, that returns an HtmlHelper object, which is the type to which we have applied our extension method.
3. Here, we pass the data to the helper method in the same way as we pass data for inline helper
4. We must also make sure that we cast the dynamic properties of the ViewBag object to the type defined by the external helper( Here: a string array).

When to use Helper Methods
1. Helper methods should be used only to reduce the amount of duplicate code in View.
2. If there is large amount of code or mark up to be written then you can either use Partial Views or Child Action.

About Built-in Helper Methods
MVC Framework provides a number of built-in helper methods. I have illustrated some of them here:
Html.CheckBox("checkbox1", false)
This will automatically generate the html markup for checkbox as shown below:
<input id="checkbox1" name="checkbox1" type="checkbox" value="true" />
<input name="checkbox1" type="hidden" value="false" />

Html.Password("password1", "val")
This will automatically generate the html markup for password control as shown below:
<input id="password1" name="password1" type="password" value="val" />

About Strongly Typed Input Helpers
For every basic input helper method there is a corresponding strongly
typed helper. These helpers can be used only with strongly-typed views.

For Example:
Below is the Strongly Typed CheckBox Helper "Html.CheckBoxFor" which represents the IsActive property of the model which is of type boolean(true/false).

Html.CheckBoxFor(x => x.IsActive)
Output:
<input id="IsActive" name="IsActive" type="checkbox" value="true" />
<input name="IsActive" type="hidden" value="false" />

Below is the Strongly Typed Password Helper "Html.PasswordFor" which represents the UserPassword property of the model.
Html.PasswordFor(x => x.UserPassword)
Output:
<input id="UserPassword" name="UserPassword" type="password" />


Article by Vaishali Jain
Miss. Jain Microsoft Certified Technology Specialist in .Net(Windows and Web Based application development)

Follow Vaishali Jain or read 127 articles authored by Vaishali Jain

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: