TagBuilder class in ASP.NET MVC

      How do we create HTML tags and control in side an extention method? I saw many used StringBuilder and Stream to genearte this. But we have built-in class for this named TagBuilder. Using this you will get a neat code and also more flxible like you add attribute and can also add styles. This is very usefule in case if your MVC control need to be rendered in side a container like DIV ot P. Look at beklow simple example

//Below method create any type of container for your MVC controls
private static TagBuilder createContainer(string tagName, object htmlAttributes)
{
TagBuilder tag = new TagBuilder(tagName);
IDictionary<string, object> htmlAttributesDictionary = new RouteValueDictionary(htmlAttributes);
tag.MergeAttributes(htmlAttributesDictionary);
return tag;
}

//Below extension method using the above general method to create one DIV for it's control
public static MvcHtmlString RadioFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
{

//Calling the method to create a container
TagBuilder modelWraper = createContainer("div", new { bgcolor = "red" });
modelWraper.GenerateId("MyDIV");

//Making this container as an MVC control
MvcHtmlString.Create(modelWraper.ToString(TagRenderMode.Normal));

//Now creating normal MVC control. Please look how attributes are adding.
TagBuilder tag = new TagBuilder("inut");
tag.Attributes.Add("type", "radio");
tag.SetInnerText("ModelValue");

//Making the created DIV as a container for the normal MVC control above created
modelWraper.InnerHtml= tag.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(modelWraper.ToString(TagRenderMode.Normal)); ;
}

It's so robust and flexible that you need to decide how to use this

Ebook Download
View all
Learn
View all