ASP.NET how to Render a control to HTML?

I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control?

Answers


This appears to work.

public string RenderControlToHtml(Control ControlToRender)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
    System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
    ControlToRender.RenderControl(htmlWriter);
    return sb.ToString();
}

Accepted answer by David Basarab will not work if control is not part of the page. a7drew's answer seems unnecessary complex - no need in Context or Server.Execute.

private string RenderControl()
{
    var sb = new System.Text.StringBuilder();
    using (var stWriter = new System.IO.StringWriter(sb))
    using (var htmlWriter = new HtmlTextWriter(stWriter))
    {
        var p = new Page();
        var ctrl = (YourControl)p.LoadControl("~/controls/building blocks/YourControl.ascx");
        ctrl.Visible = true;

        // do your own init logic if needed

        p.Controls.Add(ctrl);
        ctrl.RenderControl(htmlWriter);
        return sb.ToString();
    }
}

If your control is a web user control, this is how you can get to the HTML it emits from another page or handler:

public void GetHtmlFromMySweetControl(HttpContext context)
{
    HttpRequest httpRequest = context.Request;
    HttpResponse httpResponse = context.Response;

    string foo = httpRequest["foo"];

    Page pageHolder = new Page();
    string path = "~/usercontrols/MySweetControl.ascx";
    MySweetControl ctrl = (MySweetControl)pageHolder.LoadControl(path);
    ctrl.BindProducts(foo);
    pageHolder.Controls.Add(ctrl);

    StringWriter sw = new StringWriter();
    context.Server.Execute(pageHolder, sw, false);
    httpResponse.Write(sw.ToString());
}

Need Your Help

Jekyll - Pass a jekyll variable to a custom liquid tag

variables plugins jekyll liquid

I'm trying to work out how to pass a Jekyll variable to a liquid tag plugin.

Screen Capture Making Video

iphone

Can anyone know how to make video recording by capture the screen on iphone? I have an animation and other audio that is working simultaneously with same time and I want to record it as a video so ...