Dynamically generated ASP.NET page has no basic html structure
I wrote a page (just a class derived from System.Web.UI.Page that I want to use on other sites. I dynamically add webcontrols to the Page.Controls collection like this:
Panel p = new Panel();
p.Style.Add("float", "left");
p.Controls.Add(locLT);
Page.Controls.Add(p);
this code only displays
<div style="float:left;">
</div>
How can I add HTML, HEADER and BODY section without manual entry? Is it possible?
+2
source to share
4 answers
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());
}
}
+1
source to share
Before using MasterPages, the general way to add a header and footer for a page was to inherit from BasePage like http://gist.github.com/214437 and from Basic Header and Footer Controls. I think MasterPage is a better choice for you than BasePage above. One of the downsides to MasterPage is that you have to add asp: content to every page, but it's still better than the old one.
0
source to share