4

简单的问题,但我在上面找不到任何东西,是否可以将 asp:placeholder 的内容获取到字符串?如果可能的话,这将是很棒的服务器端。

卢克

4

2 回答 2

8

如果您只想要占位符的文本内容:

string textualContent = ((LiteralControl) PlaceHolder1.Controls[0]).Text;

退货 "Hello World"

<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>

请注意,您需要将页面指令更改为

EnableEventValidation="false"

VerifyRenderingInServerFormPage

public override void VerifyRenderingInServerForm(Control control)
{
    /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
       server control at run time. */
}

RenderControl手动调用时。

于 2013-01-14T16:06:52.700 回答
1

试试看的RenderControl方法Placeholder

我为 a 做了类似的事情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 -渲染输出

于 2013-01-14T16:02:32.070 回答