在Asp.net中从Code Behind添加Html

Vin*_*ngh 17 html asp.net dynamic code-behind c#-4.0

我想从代码后面添加HTML结构和控件到面板

<div class='Main'>
    <div class='cst'>
        First Name
    </div>
    <div class='csc'>
        <asp:Label ID="lblFirstName" CssClass="ronly" runat="server"></asp:Label>
    </div>
    <div class='cst'>
        First Name
    </div>
    <div class='csc'>
        <asp:Label ID="lblFirstName" CssClass="ronly" runat="server"></asp:Label>
    </div>        <div class='cst'>
        First Name
    </div>
    <div class='csc'>
        <asp:Label ID="lblFirstName" CssClass="ronly" runat="server"></asp:Label>
    </div>
    <div class='end'>
    </div>
</div>

  <asp:Panel runat="server" CssClass="sxpnl" ID="pnlUserdata">
        </asp:Panel>
Run Code Online (Sandbox Code Playgroud)

如果我尝试添加这样的

 HtmlGenericControl divcontrol = new HtmlGenericControl();
 divcontrol.Attributes["class"] = "sxro sx1co";
 divcontrol.TagName = "div";
 pnlUserSearch.Controls.Add(divcontrol);
 Label question = new Label();
 questionDescription.Text = "text";
 pnlUserSearch.Controls.Add(question);
Run Code Online (Sandbox Code Playgroud)

它将一个接一个地添加控件,如何使控件像上面所示那样嵌套.

Yai*_*vet 25

要将HTML附加到面板,请向面板添加LiteralControl控件:

string yourHTMLstring = "<div class='Main'>....";
pnlUserdata.Controls.Add(new LiteralControl(yourHTMLstring));
Run Code Online (Sandbox Code Playgroud)


Han*_*ing 14

不要将该子控件添加到面板,将其添加到应该是父控件的控件中:

HtmlGenericControl divcontrol = new HtmlGenericControl();
divcontrol.Attributes["class"] = "sxro sx1co";
divcontrol.TagName = "div";
pnlUserSearch.Controls.Add(divcontrol);
Label question = new Label();
questionDescription.Text = "text";
divcontrol.Controls.Add(question); // add to the new div, not to the panel
Run Code Online (Sandbox Code Playgroud)