将ASP.NET Control转换为string

下面的类可以实现将ASP.NET的Control(包括aspx页面)转换成String字符串,可以用于:

1.用邮件发送ASP.NET的内容
2.用XSLT转换页面的输出
3.ASPX页面的全局字符串的使用

C#代码

using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;

public class Render
{
 public static string RenderControl(System.Web.UI.Control control)
 {
  StringBuilder result = new StringBuilder(1024);
  control.RenderControl(new HtmlTextWriter(new StringWriter(result)));
  return result.ToString();
 }
 public static string RenderControl(System.Web.UI.TemplateControl control)
 {
  StringBuilder result = new StringBuilder(1024);
  control.RenderControl(new HtmlTextWriter(new StringWriter(result)));
  return result.ToString();
 }
 public static string RenderPage(string pageLocation)
 {
  System.Web.HttpContext context = System.Web.HttpContext.Current;
  StringBuilder result = new StringBuilder(1024);
  context.Server.Execute(pageLocation,
   new HtmlTextWriter(new StringWriter(result)));
  return result.ToString();
 }
}

 

 

 

 

/**

    public  string GetOrders(string cartid)
    {
        System.Threading.Thread.Sleep(500);
        Page page = new Page();
        CartList ctl = (CartList)page.LoadControl("~/CartList.ascx");
        ctl.CartId = cartid;
        page.Controls.Add(ctl);
        System.IO.StringWriter writer = new System.IO.StringWriter();
        HttpContext.Current.Server.Execute(page, writer, false);
        string output = writer.ToString();
        writer.Close();
        return output;
    }

 

**/

posted on 2009-12-02 17:16  西湖浪子  阅读(228)  评论(0)    收藏  举报