views:

17

answers:

1

I'm creating a Page object and adding a control to it for printing purposes. The code works, however I can not find a way to add a stylesheet link to the header. In the code I pasted I'm trying to add a link to the header and then add the header control to the page, but this causes an error:

Request is not available in this context System.Web.UI.Page.get_Request() +8700216 System.Web.UI.HtmlControls.HtmlHead.RenderChildren(HtmlTextWriter writer) +83

    Function getControlHtml() As String
    Dim sw As New StringWriter
    Dim tw As New HtmlTextWriter(sw)

    Dim pg As New Page()
    pg.EnableEventValidation = False

    Dim cssLink As New HtmlLink
    cssLink.Href = "~/css/StyleSheet.css"
    cssLink.Attributes.Add("rel", "Stylesheet")
    cssLink.Attributes.Add("type", "text/css")        

    'works without this code
    Dim head As New HtmlHead
    head.Controls.Add(cssLink)
    pg.Controls.Add(head)

    Dim frm As New HtmlForm
    pg.Controls.Add(frm)
    frm.Attributes.Add("runat", "server")
    frm.Controls.Add(pnlMACForm)
    pg.DesignerInitialize()
    pg.RenderControl(tw) ' <--

    Return sw.ToString()
End Function
+1  A: 

You really can't create a page dynamically in the way that you're thinking. All you're doing is creating the Page object, but you haven't done it via the ASP.net pipeline.

That means that the Page object hasn't been set as the IHttpHandler for the request (and consequently hasn't been handed an HttpApplication containing all the context objects it needs, like Request and Response), and calling any of the page lifecycle methods (like RenderControl) are going to fail.

ASP.Net webforms does not have an easy way of rendering a page to a string. Creating an "unattached" page object and adding controls to it will unfortunately not lead you very far. If you really need to render controls outside of the page lifecycle for some reason, you may be able to do it by loading and rendering .ascx files, but this may not be dynamic enough for your needs.

Can I ask what you're trying to do by getting the HTML from these controls?

womp
Jay Douglass
I'm going to use another method that will work, just with more hand coding of html.
Jay Douglass