Creating MVC Custom Helper Methods

Inline Helper Method: We can create inline helper method using @helper tag.

and once helper has defined, we can easily use in body as follow.

<div> Here are the fruits: @ListArrayItems(ViewBag.Fruits) </div>

although inline helper looks like method but its does not have any return type.

We may also include Razor HTML tag inside inline helper.

It’s very useful to design HTML with inline helper.  and the HTML render in above example with combination of <ul> and <li>.

Inline helpers are convenient, but they can be used only from the view in which they are declared. 

For that we will create an external helper. create a new class CustomHelpers.cs .

It is same like we have created with inline helper. it takes an array of strings and generates an HTML ul element, containing a li element for each string in the array.

The easiest way to create HTML inside  helper is TagBuilder.

TagBuilder tag = new TagBuilder(“ul”);

The result of an HTML helper method is an MvcHtmlString object, the contents of which are written
directly into the response to the client

return new MvcHtmlString(tag.ToString());

The result of an HTML helper method is an MvcHtmlString object

Helper can easily use in Razor view as follow.

@model string
@using HelperMethods.Infrastructure  // Where Infrastructure is folder where customerhelper.cs is created. 

Then in body

Here are the fruits: @Html.ListArrayItems((string[])ViewBag.Fruits)

We have called custom helper @using  tag inside view, but if you are developing a lot of custom helpers then you will want to add the namespaces that contain them to the /Views/Web.config file so that they are always available in your views.

We refer to the helper using @Html.<helper>, where <helper> is the name of the extension method