Wednesday, February 12, 2014

Step by step how to create Custom HTML Helpers with Extension Methods

        By Carmel Schvartzman

In this tutorial we'll learn how to Create HTML Helpers with Extension Methods in ASP.NET MVC 4
An Html Helper is a class designed for rendering HTML controls to the Views. They are just methods which return strings representing HTML tags. They support several extension methods representing the different controls such as forms, textboxes, labels, dropdownlists, routelinks ( "< a >" ) , actionlinks ( "< a >" ) ,textareas, passwords, listboxes, checkboxes, radiobuttons, hidden fields, editors, and validation code.

We'll want to create an HTML Helper using an Extension method, to add a custom Label tag to the web page, as follows:

We'll create a custom HTML Helper to render a Label . The custom HTML Helper will be compiled in a separate .DLL , a win Class Library application, where you could store your HTML Helpers, and reuse them in every MVC app you create. 
So add a new  Class Library application  to your solution, and name it CustomHelpers:

Add a reference to System.Web.Mvc:

Change the class's name to "MyHelpers", and add the following "Label" Extension method , with the 4 parameters TargetControl, Class, Style, and DisplayText, appended to the "this" parameter:

The parameters represent the target control for the Label, the CSS class of the tag, the inline style and the text to be displayed by the Label.
Next, insert the following String.Format to render the Label tag with the incoming arguments:

Build the DLL and add a reference to it to the MVC project:

To use the custom HTML Helper we must create our own View, so first let's create a new Controller called "NewViewController", and then add a View to the Index Action method. So right click over the Controllers folder, and add a new Controller:

Name it "NewViewController", and select the template "Empty MVC Controller":

Open the Controller file and find the "Index" Action method:

Right click on it and select the option "Add View":

On the dialog, let the name be "Index", select the "ASPX" View engine, and choose a master page:

Open the View we just created, and create the Form object,  taking care of its tags:

Also, add a button in order to submit the form:

Also within the Index View, add the "Import" directive to allow using the DLL Namespace :

Then, add your new custom HTML Helper to the Form:

Notice the arguments of the Label extension method: we specify the target control, the CSS class , if any, the CSS inline style and the text.

Rebuild your application and browse to the "NewView" web page, to see your custom Label:

In this tutorial we've learned how to to Create HTML Helpers with Extension Methods in ASP.NET MVC 4, storing them in a separate DLL
That's all!! 
Happy programming.....

כתב: כרמל שוורצמן