非原创。来自博客园老赵。
public class ViewManager<T> where T : System.Web.UI.UserControl
{
private System.Web.UI.Page m_pageHolder; public T LoadViewControl(string path)
{
this.m_pageHolder = new System.Web.UI.Page(); return (T)this.m_pageHolder.LoadControl(path);
} public string RenderView(T control)
{
StringWriter output = new StringWriter(); this.m_pageHolder.Controls.Add(control);
HttpContext.Current.Server.Execute(this.m_pageHolder, output, false); return output.ToString();
}
}
Control control = viewManager.LoadViewControl("~/Controls/" + name);
context.Response.Write(viewManager.RenderView(control));