当前位置:  开发笔记 > 后端 > 正文

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

如何解决《ASP.NET如何将控件渲染为HTML?》经验,为你挑选了3个好方法。

我有任何ASP.NET控件.我想要HTML字符串如何获取控件的HTML字符串?



1> David Basara..:

这似乎有效.

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


StringWriter和HtmlTextWriter都实现了IDisposable,因此您可能希望将它们包装在using(){}块中.此外,将其作为"Control"的扩展方法可能很有用,因此您可以从实例成员中调用它.

2> avs099..:

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



3> a7drew..:

如果您的控件是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());
}

推荐阅读
勤奋的瞌睡猪_715
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有