Question

I'm trying to programmatically render an aspx page to a string. The rendering is to be done from a console app. For now I've gotten it work with programmatically declared controls in the aspx page, which is all fine and dandy. But what about statically declared controls? It there any way to achieve that?

Example code: Page rendering:

static string RenderPage() {

        ClassLibrary1.FormlessPage pageHolder = (ClassLibrary1.FormlessPage)new WebApplication1.WebForm1();
        pageHolder.DesignerInitialize();

        StringWriter output = new StringWriter();
        HttpRequest httpRequest = new HttpRequest("", "http://localhost/", "");
        HttpResponse httpResponse = new HttpResponse(output);
        HttpContext context = new HttpContext(httpRequest, httpResponse);
        context.Server.Execute(pageHolder, output, false);

        return output.ToString();
    }

Formless page class

namespace ClassLibrary1 {
public class FormlessPage : System.Web.UI.Page {
    public override void VerifyRenderingInServerForm(Control control) {}
}
}

Now, when I declare controls in WebForm1 (which is in a references web application project, but behavior is the same when done within the same project) they render just fine.

public partial class WebForm1 : ClassLibrary1.FormlessPage {
    protected void Page_Load(object sender, EventArgs e) {
        this.Controls.Add(new TextBox() { ID = "tbSomeText", Text = "default text" });
    }
}

...but static html and statically declared controls are not rendered.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
...blah...blah...
<form id="form1" runat="server">
<div>
    text
    <asp:TextBox runat="server" ID="tbSomething"></asp:TextBox>
</div>
</form>
...blah...blah...

Is there any way to completely fake this behavior and achieve the markup rendering too? Rendered output from the above is simply:

<input name="tbSomeText" type="text" value="default text" id="tbSomeText" />

No correct solution

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