Question

I have a 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.

Was it helpful?

Solution 2

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();
        }
    }

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top