views:

97

answers:

4

Hi, 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?

A: 

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.

Jason Berkan
A: 

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.

orjan
A: 

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.

Bryan
+1  A: 

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

}
rick schott