ASP.NET如何将控件渲染为HTML?

时间:2008-09-12 13:17:46

标签: .net asp.net

我有任何ASP.NET控件。我想要HTML字符串怎么做我得到控件的HTML字符串?

3 个答案:

答案 0 :(得分:42)

这似乎有效。

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

答案 1 :(得分:8)

如果控件不是页面的一部分,则David Basarab接受的答案将不起作用。 a7drew的回答似乎没那么复杂 - ContextServer.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();
    }
}

答案 2 :(得分:6)

如果您的控件是Web用户控件,则可以使用以下方式获取从其他页面或处理程序发出的HTML:

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