Output clean HTML markup for data driven dynamic HTML
June 1, 2016
The HTML helper method Html.BeginForm is a useful
way to dynamically create <form> tags. It
would be useful to be able to do this for other HTML tags so that
the HTML output is dynamically generated keeping your markup clean.
In the following example, _dataProvider.GetAdvertDataAttributes()
returns an IDictionary<string, object> and defines any
additional data attributes required on the component:
Usually AdvertDataAttributes would require expanding into a string to output in
the Razor view, for example:
This requires code to convert the dictionary into a string
ensuring that the attributes are encoded properly using
HttpUtility.HtmlAttributeEncode. Also, it could lead to
class="" being output to the page.
Using the extension method for System.Web.Mvc.HtmlHelper
and supporting MvcTag class found at the end of the post, it
becomes a lot simpler to create the dynamic HTML required.
The benefit of this is that if the model variables AdvertClass
and AdvertDataAttributes were null, then the HTML output
would not have any empty attributes, i.e.
To achieve this, the following HtmlHelper extension method and
supporting MvcTag class are required: