The MVC platform: the TagBuilder class
In the last posts we’ve seen that the platform introduces several helpers for generating the HTML for the controls you want to put in a page. Today we’re going to look at the class that is responsible for outputting that HTML and that is used internally by all those helpers: the TagBuilder class.
The only public constructor of the TagBuilder class receives the name of the HTML tag you want to generate. Besides that, you can also set its inner HTML (by using the InnerHtml property) or the text the control should render (by using the SetInnerText method). Another of the properties exposed by the class is the IdAttributeDotReplacement property. This property is used for indicating the character that should be used when rendering the client ID for composite names. For instance, the TextBox helper method can be used like this:
<%= Html.TextBox(“User.Name”) %>
In the old days, you’d get User.Name as the id of HTML INPUT that is generated by that line. Unfortunately, that didn’t work very well when you’re using JQuery. That’s why this property was added in this release. Btw, you should know that the current release uses the ‘_’ char as the separator. If you need to change that char to something else, then you should set the Html.IdAttributeDotReplacement property. BY doing this, you’ll end up setting the IdAttributeDotReplacement property on the TagBuilder instance that is used to generate the HTML.
Besides the text/inner HTML and the separator used in “complex names”, there are also other methods which you can use. For instance, you can add an existing css class by calling the AddCssClass method. You can also merge attributes by calling the MergeAttribute method. This method will let you override or append a specific value to an attribute that is going to be rendered on the HTML that is generated by this class. There really isn’t much to say about this class. The important thing to keep in mind is that you should use it when you’re building your own HTML helpers.
And that’s all for today. More about the MVC on the next posts.