ASP. NET method example summary of dynamically adding HTML elements

  • 2021-09-12 00:46:57
  • OfStack

In this paper, the method of dynamically adding HTML elements to ASP. NET is described with examples. Share it for your reference, as follows:

When developing web using asp. net, the < head > < /head > The information in can be dynamically specified through the cs file of asp. net.

1. Add style sheets dynamically


/* Dynamically add style sheets */
HtmlLink link = new HtmlLink();
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("href", "/css/base.css");
this.Header.Controls.Add(link);

2. Add styles dynamically


/* Dynamic increase style */
Style style = new Style();
style.Font.Size = 20;
style.ForeColor = System.Drawing.Color.Navy;
style.BackColor = System.Drawing.Color.LightGray;
this.Header.StyleSheet.CreateStyleRule(style, null, "body");

3. Dynamically increase Meta


/* Dynamic increase Meta*/
HtmlMeta meta = new HtmlMeta();
meta.Name = "keywords";
meta.Content = "Your keywords here";
this.Header.Controls.Add(meta);
meta = new HtmlMeta();
meta.Name = "company";
meta.Content = "microsoft";
this.Header.Controls.Add(meta);
meta = new HtmlMeta();
meta.Name = "date";
meta.Content = DateTime.Now.ToString("yyyy-MM-dd");
meta.Scheme = "YYYY-MM-DD";
this.Header.Controls.Add(meta);

4. Add js files dynamically


/* Dynamic increase js Documents */
HtmlGenericControl si = new HtmlGenericControl();
si.TagName = "script";
si.Attributes.Add("language", "javascript");
si.Attributes.Add("type", "text/javascript");
si.Attributes.Add("src", "/js/common/base.js");// Pay attention to the writing of the path 
this.Page.Header.Controls.Add(si);

Matters needing attention

Using the above code, < head > The label must be marked with runat = "server" (server control).


<head runat="server">
</head>

For more readers interested in asp. net related contents, please check the topics of this site: "Summary of asp Optimization Skills", "Summary of asp String Operation Skills", "Summary of asp. net Operation Skills of XML", "Summary of asp.net File Operation Skills", "Summary of asp. net ajax Skills" and "Summary of asp. net Cache Operation Skills".

I hope this paper is helpful to everyone's asp. net programming.


Related articles: