简体   繁体   English

在代码隐藏中动态创建HTML标记

[英]Creating HTML tags dynamically in code-behind

How can I add HTML tags to aspx file from the code-behind? 如何从代码隐藏中将HTML标记添加到aspx文件?

When I create new object 当我创建新对象时

Graph MyChart = new Graph();

I want it add a tag for this object 我想为它添加一个标签

<Graph id="MyChart" runat="server" Height="500px"></Graph>

What is the solution for that? 解决方案是什么?

Not sure if we are talking about a .NET control or HTML on the fly, I give examples of both. 不确定我们是否正在讨论.NET控件或HTML,我举两个例子。

This will add it to the end of the page, but I suggest you use a PlaceHolder to control where it gets added: 这会将它添加到页面的末尾,但我建议您使用PlaceHolder来控制添加位置:

Graph MyChart = new Graph();
MyChart.ID = "MyChart";
Page.Controls.Add(MyChart);

//genericcontrol example
HtmlGenericControl NewControl = new HtmlGenericControl("graph");

// Set the properties of the new HtmlGenericControl control.
NewControl.ID = "MyGraph";
Page.Controls.Add(NewControl);

PlaceHolder example: PlaceHolder示例:

 <form id="form1" runat="server">
      <h3>PlaceHolder Example</h3>
      <asp:PlaceHolder id="PlaceHolder1" 
           runat="server"/>
   </form>

  protected void Page_Load(Object sender, EventArgs e)
  {
     Graph MyChart = new Graph();
     MyChart.ID = "MyChart";
     PlaceHolder1.Controls.Add(MyChart);

    //genericcontrol example
    HtmlGenericControl NewControl = new HtmlGenericControl("graph");

    // Set the properties of the new HtmlGenericControl control.
    NewControl.ID = "MyGraph";
    PlaceHolder1.Controls.Add(NewControl);

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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