In the last article we introduced the concepts behind the ASP.NET MVC Helpers and how they help to facilitate when developing ASP.NET MVC application. In this article we are going to see different ways of implementing ASP.NET MVC Helpers.
Extending HtmlHelper Class Using Extension Methods:
Creating ASP.NET MVC Helper is not rocket science and can be performed just by extending the HtmlHelper class using extension methods. Inside the extension method you can return the HTML of the control you are trying to build. The View will consume the HTML and display the control. The main part of this process is to generate the HTML for the control. Let's take a look at different ways you can accomplish it.
Building HTML String Manually:
The easiest and the simplest way to create a new HTML helper is to return a string from the extension method. The code below shows how to implement a simple HTML helper to create a customized Blue TextBox control.
In the above code we are simply creating the HTML for the control by returning the string back to the view. The view will use the BlueTextBox as shown below:
As, expected the HTML generated by the BlueTextBox will be the same HTML that you have returned from the BlueTextBox extension method as shown below:
This was just one of the ways to develop your HTML helpers. In the next section we will demonstrate how you can use the TagBuilder class to create HTML helpers.
Using TagBuilder Class to Construct HTML:
The TagBuilder class is part of the System.Web.Mvc assembly and it allows you to create HTML tags. The purpose of the TagBuilder class is to provide extra assistence when developing HTML controls. It removes the string concatenation problems from the equation and provide an easy way to construct HTML. The code below shows how to use the TagBuilder class to construct the BlueTextBox control.
Since, the input type HTML elements can be of different type namely radio, checkbox, textbox, password etc. You can specify the "type" attribute to represent the type of the control you want to create.
The above code will produce the following HTML:
The next method uses the Webforms control to render the HTML to the client.
Using Webforms ASP.NET Controls:
You can always use Webform controls to render the HTML of the control to a TextWriter and return the generated HTML to the view. The implementation is shown below:
If you are not looking for much customization then you can use the above method and use the already existing Webforms controls in your ASP.NET MVC application.
HTML helpers are easy to create and there are multiple ways to implement them. Depending on the scenario you can choose any of the above methods to create your Html helpers. In the next article we will implement the SelectList HTML helper which can be used to create RadioButtonList, CheckBoxList etc.