asp:占位符内容到字符串

时间:2013-01-14 15:57:50

标签: c# asp.net string placeholder

简单的问题,但我找不到任何内容,是否有可能将asp:占位符的内容添加到字符串中?如果可能的话,这对服务器端来说会很棒。

2 个答案:

答案 0 :(得分:7)

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

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"

并覆盖VerifyRenderingInServerForm

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

手动调用RenderControl时。

答案 1 :(得分:1)

尝试使用RenderControl的{​​{1}}方法。

我为Placeholder做了类似的事情,但是HyperLink继承自Placeholder,它应该完全相同。像这样:

System.Web.UI.Control

我写了一篇关于这个主题的简短文章:http://www.tomot.de/en-us/article/3/asp.net/create-a-control-in-the-codebehind-and-retrieve-its-rendered-output