Question

i wrote a page (only class that derives from System.Web.UI.Page, that i want to use in more websites. I dynamically add webcontrols to Page.Controls collection like this:

Panel p = new Panel();
p.Style.Add("float", "left");
p.Controls.Add(locLT);
Page.Controls.Add(p);

this code renders only

<div style="float:left;">
</div>

How can i add HTML, HEADER and BODY section without manually write this? Is it possible?

Was it helpful?

Solution

I recommend MasterPages but you can do this:

public class CustomBase : System.Web.UI.Page  
{    
    protected override void Render( System.Web.UI.HtmlTextWriter textWriter ) 
    {
        using (System.IO.StringWriter stringWriter = new System.IO.StringWriter())
        {
             using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
             {    
                 LiteralControl header =new LiteralControl();
                 header.Text = RenderHeader(); // implement HTML HEAD BODY...etc

                 LiteralControl footer = new LiteralControl();
                 footer.Text = RenderFooter(); // implement CLOSE BODY HTML...etc

                 this.Controls.AddAt(0, header); //top
                 this.Controls.Add(footer); //bottom

                 base.Render(htmlWriter); 
             }
        }

        textWriter.Write(stringWriter.ToString());
    }       

}

OTHER TIPS

I don't believe there is any way to automatically generate the tags, but you can create your own Render method that outputs the required basic HTML framework.

Before using MasterPages a common way to add header and footer for a page was to inherit from a BasePage like http://gist.github.com/214437 and from the BasePage load header and footer controls. I think that a MasterPage is better choice for you than the BasePage above. One of the drawbacks with a MasterPage is that you have to add asp:content at every page but it's still better than the old way.

If your "page" is completely dynamic and has no aspx front-end (I didn't realize this was possible?!)... then what you really want is probably a custom HttpHandler rather than inheriting from Page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top