[ASP.NET MVC] Views – Custom HTML Helpers

Html Helper methods help you generate commonly used HTML fragments. In most cases, the built-in helpers will meet your needs. But there are some cases you want to generate your custom HTML fragments. By extending the “HtmlHelper” class, you can create your own helper method.

1. Using @helper Syntax

You can define a helper method directly in a view by using the “@helper” razor syntax.

@helper TruncateDescription(string input, int maxLength)
{
  if (input.Length <= maxLength)
  {  
    @input
  }
  else
  {
    @input.Substring(0, maxLength)<text>...</text>
  }
}
@foreach (var item in Model)
{
  <tr>
    <td>
    @TruncateDescription(item.Description, 20)
    </td>
  </tr>
}

2. Using Extension Methods

If you want to use your custom helper method across your site, you need to define the extension method to the “HtmlHelper” class.

  • Create a “Helpers” folder in your project (Optional)
  • Create a static class
  • Define a static method with the first parameter “this HtmlHelper helper
namespace MyApp.Helpers
{
  public static class MyHtmlHelpers
  {
    public static string Truncate(this HtmlHelper helper, string input, int maxLength)
    {
      if (input.Length <= maxLength)
        return input;
      else
        return input.Substring(0, maxLength) + "...";
    }
  }
}

To refer to the method in a view, you need to include the namespace with the “using” statement

@using MyApp.Helpers
@foreach (var item in Model)
{
  <tr>
    <td>
      @Html.TruncateDescription(item.Description, 20)
    </td>
  </tr>
}

4 thoughts on “[ASP.NET MVC] Views – Custom HTML Helpers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s