Custom Label Helper in MVC3 Razor

  1. In MVC3 Razor we have HTML helpers to render different controls. 
  2. Instead of using these helpers we can create our own helper classes and methods and use them as we want.
  3. The creation of custom helpers provides flexibility to change the attributes and style of the control that renders.
  4. In this article we will create Custom HTML helper for Label to render text.

From here we are going to create Custom HTML helper for Label control :

We will create a new folder to contain classes for custom helpers as shown below.

In the above screenshot we have created a folder named CustomHelpers to contain helper classes.
After creating the folder, add a class file. We will name it as CustomLabel.cs as we are creating custom helper for Label control.

As shown above we have added a CustomLabel class file that contains the code to render label control.
In this file we will create a static class having a static method that renders the label control.
The class is created as shown below :

In the above screenshot we have created a static class. We have created a static method named Custom_Label.
        This method accepts name, value and htmlAttributes object as parameter. The number and name of parameters can be changed. 
        In the above code we are using name attribute to set the name attribute. The value parameter is used to set the value or innerText of Label control which is rendered on UI. 
        The htmlAttributes object contains additional attributes passed as an object. We can assign CSS classes and properties using htmlAttributes object.
        The method created above is extension method, and first parameter adds this method to System.Web.Mvc namespace. On view we can access this method using @Html. This method returns MvcHtmlString object. The MvcHtmlString represents a HTML-encoded string that should not be encoded again.
        Inside the method we are creating a Label tag using TabBuilder class. We are then setting the attributes of the object with the parameters received at method. Finally we returns the Label control in MvcHtmlString format.

View :

In the view we are passing the required attributes for the Custom Helper. We are also passing the CSS class to apply as a part of htmlAttributes object.

Before running the application add the namespace reference of the custom class in Web.config so that the method is accessed anywhere in the solution.

We have added the reference of namespace containing the custom class in Web.config.

UI :

As we can see in the above screenshot the text that is passed as paremeter to the Custom Label helper is rendered on UI.

Rendered HTML :

    <Label class="LabelText" for="CustomHelpers">This is demo for Custom Helper</Label>

This is how we can create a Custom Helper in MVC3 Razor and fulfill our specific project needs.


Post a Comment