ASP.NET MVC: Encapsulate Html helper

facebooktwittergoogle_plusredditpinterestlinkedinmail

In ASP.NET MVC we have lots of predefined html helper class to render html controls in view. If we are using the predefined control, then we need to specify the common things like common style in each control, then only we would get the same style in everywhere in the application. Suppose you have 1000 + textboxes in your application. See the following code.

  @Html.TextBoxFor(r => r.BankInfo, new { @class = "form-control"})

You have to give class=”form-control” in 1000 times. What do you think? Is it a good practice? It’s not a good practice. We can encapsulate our html helper and write common things in one place. Look at the following custom attribute.

 public static IHtmlString CustomTextBoxFor<TModel, TProperty>(
                  this HtmlHelper<TModel> helper,
                  Expression<Func<TModel, TProperty>> expression)
        {
            return helper.TextBoxFor(expression, new
            {
                @class = "form-control"
            });
        }

Consume this in view like

 @Html.CustomTextBoxFor(r => r.BillingInfo)

This same way we can write in TextBox

  public static IHtmlString CustomTextBox(
                    this HtmlHelper helper,
                   string propertyName)
        {
            return helper.TextBox(propertyName, new
            {
                @class = "form-control"
            });
        }

For LabelFor and Label

   public static IHtmlString CustomLabelFor<TModel, TProperty>(
                     this HtmlHelper<TModel> helper,
                     Expression<Func<TModel, TProperty>> expression)
        {
            return helper.LabelFor(expression, new
            {
                @class = "form-control"
            });
        }
    public static IHtmlString CustomLabel(
                    this HtmlHelper helper,
                   string propertyName)
        {
            return helper.Label(propertyName, new
            {
                @class = "form-control"
            });
        }

You might also like:

The following two tabs change content below.

Tom Mohan

Tom Mohan is a technologist who loves to code and build. He enjoys working on Microsoft Technologies. Tom specializes in ASP.NET MVC, Web API , Azure, C# ,WPF, SQL etc and holds a Bachelor engineering degree in Computer Science. Certification : MCSD , MCTS
  • joe

    Nice post