占位符内容转换为字符串
本文关键字:字符串 转换 占位符 | 更新日期: 2023-09-27 17:52:50
简单的问题,但我找不到任何东西,是否有可能得到一个asp:占位符的内容字符串?如果可能的话,这将是伟大的服务器端。
《路加福音》如果您只想要占位符的文本内容:
string textualContent = ((LiteralControl) PlaceHolder1.Controls[0]).Text;
返回
"Hello World"
for:
<asp:PlaceHolder ID="PlaceHolder1" runat="server">Hello World</asp:PlaceHolder>
如果您还想获得渲染控件(及其所有子控件)的html:
System.IO.TextWriter tw = new System.IO.StringWriter();
HtmlTextWriter h = new HtmlTextWriter(tw);
PlaceHolder1.RenderControl(h);
string html = tw.ToString();
对于这个aspx (GridView
绑定了一些相同的数据):
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
<asp:Label ID="LblTest" runat="server">Test-Label</asp:Label>
<asp:TextBox ID="TxtTest" runat="server" Text="Foo"></asp:TextBox>
<asp:GridView runat="server" ID="GridView1"></asp:GridView>
<textarea name="TextArea1" rows="2" cols="1">
First line
Second line
</textarea>
</asp:PlaceHolder>
这个HTML将被生成(取决于浏览器):
<span id="MainContent_LblTest">Test-Label</span><input name="ctl00$MainContent$TxtTest" type="text" value="Foo" id="MainContent_TxtTest" /><div>
<table cellspacing="0" rules="all" border="1" id="MainContent_GridView1" style="border-collapse:collapse;">
<tr>
<th scope="col">ID</th><th scope="col">Text</th>
</tr><tr>
<td>1</td><td>Row #1</td>
</tr><tr>
<td>2</td><td>Row #2</td>
</tr><tr>
<td>3</td><td>Row #3</td>
</tr><tr>
<td>4</td><td>Row #4</td>
</tr><tr>
<td>5</td><td>Row #5</td>
</tr>
</table>
</div>
<textarea name="TextArea1" rows="2" cols="1">
First line
Second line
</textarea>
注意你需要把你的page指令改成
EnableEventValidation="false"
和覆盖Page
中的VerifyRenderingInServerForm
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
手动调用RenderControl
尝试Placeholder
的RenderControl
方法
我为HyperLink
做了这样的事情,但是作为Placeholder
继承自System.Web.UI.Control
,这应该是完全相同的。像这样:
StringBuilder sb = new System.Text.StringBuilder();
using (var stringWriter = new System.IO.StringWriter(sb))
{
using (var htmlTextWriter = new System.Web.UI.HtmlTextWriter(stringWriter))
{
YourPlaceHolder.RenderControl(htmlTextWriter);
}
}
return sb.ToString();
我写了一篇关于这个话题的短文:http://www.tomot.de/en-us/article/3/asp.net/create-a-control-in-the-codebehind-and-retrieve-its-rendered-output