从 Asp.net 中的代码隐藏添加 Html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20854437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Html from Code Behind in Asp.net
提问by Vinay Pratap Singh
I want to add HTML structure and control like this from code behind into a panel
我想将这样的 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>
If i try to add like this
如果我尝试像这样添加
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);
It will add controls one after another, how can i make controls go nested like that as shown above.
它将一个接一个地添加控件,我怎样才能让控件像上图那样嵌套。
采纳答案by Hans Ke?ing
Don't add that child control to the panel, add it to the control that should be the parent:
不要将该子控件添加到面板中,将其添加到应该是父控件的控件中:
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
回答by Yair Nevet
For appending HTML to your panel, add a LiteralControl
control to your panel:
要将 HTML 附加到您的面板,请向您的面板添加一个LiteralControl
控件:
string yourHTMLstring = "<div class='Main'>....";
pnlUserdata.Controls.Add(new LiteralControl(yourHTMLstring));
回答by mrbengi
<div id="Div1" runat="server">
Div1.InnerText = "Text";
回答by Saurabh
Make the div runat="server"
制作div runat="server"
<div id="d" runat="server"></div>
and add the controls inside div like below
并在 div 中添加控件,如下所示
d.Controls.Add();
回答by Chirag
- Take one local string variable TEMP.
- Create same html as you want to display on screen and store it in variable TEMP.
- You can take html creation of control in separate function based on requirement.
- Place that created html as innerHTML to your panel/div.
- 取一个本地字符串变量 TEMP。
- 创建与您想要在屏幕上显示相同的 html 并将其存储在变量 TEMP 中。
- 您可以根据需要在单独的功能中使用 html 创建控件。
- 将创建的 html 作为 innerHTML 放置到您的面板/div。
That's it...
就是这样...