开发者

Getting the content of an ASP.NET System.Web.UI.WebControls.PlaceHolder

I have a开发者_JS百科 server control that has a PlaceHolder that is an InnerProperty. In the class when rendering I need to get the text / HTML content that is supposed to be in the PlaceHolder. Here is a sample of what the front end code looks like:

<tagPrefix:TagName runat="server">
    <PlaceHolderName>
      Here is some sample text!
    </PlaceHolderName>
</tagPrefix:TagName>

This all works fine except I do not know how to retrieve the content. I do not see any render methods exposed by the PlaceHolder class. Here is the code for the server control.

public class TagName : CompositeControl
{
    [TemplateContainer(typeof(PlaceHolder))]
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public PlaceHolder PlaceHolderName { get; set; }

    protected override void RenderContents(HtmlTextWriter writer)
    {
       // i want to retrieve the contents of the place holder here to 
       // send the output of the custom control.
    }        
}

Any ideas? Thanks in advance.


I just found the solution. I did not see the render methods because of the context of how I was using the PlaceHolder object. Eg I was trying to use it as a value and assign it to a string like so:

string s = this.PlaceHolderName...

Because it was on the right hand side of the equals Intellisense did not show me the render methods. Here is how you render out a PlaceHolder using and HtmlTextWriter:

   StringWriter sw = new StringWriter();
   HtmlTextWriter htw = new HtmlTextWriter(sw);
   this.PlaceHolderName.RenderControl(htw);
   string s = sw.ToString();


Posting this as a second answer so I can use code formatting. Here is an updated method that uses Generics and also uses the 'using' feature to automatically dispose the text / html writers.

    private static string RenderControl<T>(T c) where T : Control, new()
    {
        // get the text for the control
        using (StringWriter sw = new StringWriter())
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            c.RenderControl(htw);
            return sw.ToString();
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜