Create HTML Helpers using the TagBuilder class
Before starting the implementation, there are a few things to know about MVC and TagBuilder
and HtmlHelper
classes.
Component Overview
TagBuilder
Namespace : System.Web.Mvc
This class provides the methods and properties that allow you to create HTML elements.
HtmlHelper
Namespace : System.Web.Mvc
This class provides methods that make it easy to create HTML code. All methods generate returned HTML code as String
.
IHtmlString
Namespace : System.Web
This interface exposes the ToHtmlString
method which is used by MVC to render the control in the view.
Implementation
(This article is illustrated with code snippets. Complete sources are available on Github : TagBuilderHtmlHelperTutorial)
We start by creating a new HtmlTag
class that implements the IHtmlString
interface.
This class HtmlTag
encapsulates an instance of TagBuilder
that will be used for the creation of HTML code when calling the method ToHtmlString
.
We also override the ToString
method. The ToString
and ToHtmlString
methods will return the same result, which is a common practice for HtmlHelper
.
We then create several extension methods that use HtmlTag
objects :
We add components for Bootstrap :
Firstly, we define a ButtonStyle
enum representing the different Bootstrap button classes
Then we add specialized extension methods :
Finally we add some extension methods specific to the WebApp project :
Usage
All sources are available on Github :TagBuilderHtmlHelperTutorial