简体   繁体   中英

How to add text “Hello World” to WebControl like <h1>Hello World</h1>

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:

  1. HtmlGenericControl... can use with var var h3_hgc = new HtmlGenericControl("h3"); h3_hgc.InnerText = "Hello World";

  2. LiteralControl which is derived from WebControl LiteralControl hwLiteralControl = new LiteralControl("Hello World"); wc.Controls.Add(hwLiteralControl);

Headings are not server webcontrols but html elements. If you need to create it dynamically:

var h3 = new HtmlGenericControl("h3");
h3.InnerHtml = "Hello World";
container.Controls.Add(h3);

Where container is the control where you want to add it.

The way I like to put literal strings into the pages is by using the Literal tag

Default.aspx:

<h1><asp:Literal ID="litHeader" runat="server" /></h1>

Default.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    litHeader.Text = "Hello World";
  }
}

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:

<h1>Hello World</h1>

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:

using Microsoft.Security.Application;

protected void Page_Load(object sender, EventArgs e)
{
  /* username is pulled from a datastore*/
  if (!IsPostBack)
  {
    litHeader.Text = Encoder.htmlEncode(username);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM