Need help finding how to add text to a web control in asp.net. Looking for the simplest solution if possible or using a control builder if thats simple.
Example html to be generated by WebControl:
<h3>Hello World</h3>
Example of my best attempt so far:
WebControl wc = new WebControl(HtmlTextWriterTag.H3);
wc.????
Answered below at least two versions:
-
HtmlGenericControl… can use with var
var h3_hgc = new HtmlGenericControl(“h3”);
h3_hgc.InnerText = “Hello World”; -
LiteralControl which is derived from WebControl
LiteralControl hwLiteralControl = new LiteralControl(“Hello World”);
wc.Controls.Add(hwLiteralControl);
The way I like to put literal strings into the pages is by using the Literal tag
Default.aspx:
Default.aspx.cs:
What I like about using the Literal control is there is no extra markup that gets rendered to the HTML. This works great anytime I want to display anything to the screen but will not be referencing it later to get values out.
How it Rendered:
Edit:
The example above is a simple demo approach. When output anything to the screen you want to make sure you protect against Cross Site Scripting attacks. Since you are using ASP.Net Web Forms, I would get the NuGet package “Antixss” from Microsoft. (Use Antixss’ Encoder.HtmlEnocde() over Server.HtmlEncode, heres why)
Here is how you would use it:
Default.aspx.cs: