Generating HTML string in C#

The proper way to generate html string in C#

From time to time you get to the point where you have to generate some HTML in C# code.

Of course, the easier way is to concatenate string and return that as a result of a method. This is not the most elegant solution and it is only fine for some short string.

I case you have some more complicated HTML structure, code becomes non-maintainable because of a lot string formats and concatenating.

Although this is the worst way to do it, a lot of people go with this approach which causes a lot of headaches to anyone who needs to change that.

The following is an approach which is based on HtmlGenericControl class in System.Web.UI.HtmlControls namespace. Basically you instantiate controls and add then into controls collection of a parent control.

Att the end, you call the render method and you get structured HTML string in the end.

            StringBuilder sbControlHtml = new StringBuilder();
            using (StringWriter stringWriter = new StringWriter())
                using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
                    //Generate container div control
                    HtmlGenericControl divControl = new HtmlGenericControl("div");
                    divControl.Attributes.Add("data-description", "some custom value");
                    divControl.InnerText = "div text content";

                    //Generate HTML5 number input control
                    HtmlGenericControl numberControl = new HtmlGenericControl("input");
                    numberControl.Attributes.Add("type", "number");
                    numberControl.Attributes.Add("id", "txtNumber");
                    numberControl.Attributes.Add("name", "txtNumber");

                    //Add number input to container div

                    //Generate HTML string and dispose object 

This is a lot more elegant way to build HTML in a C# method and it is much easier to maintain it because there ano string concatenations and formatting.


Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

About the author


Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus


read more


read more

Umbraco CMS

read more


read more

Comments for this article