您的位置:首页 > 编程语言 > ASP

动态的呈现页面. 模拟ASP.NET UpdatePanel部分更新配合WebServices.

2009-09-24 17:37 519 查看
在平常工作中,我们经常遇到需要将页面GridView导出到EXCEL, 通常做法我们就是动态构建以个Page及Form,然后写到返回流(Response)中.

using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Reflection;
using System.Web.UI.HtmlControls;

public class ViewManager
{
public static string RenderView(string path)
{
return RenderView(path, null);
}

public static string RenderView(string path, object data)
{
Page pageHolder = new Page();
UserControl viewControl = (UserControl) pageHolder.LoadControl(path);
HtmlForm hf = new HtmlForm();
hf.Attributes.Add("runat", "server");

if (data != null)
{
Type viewControlType = viewControl.GetType();
FieldInfo field = viewControlType.GetField("Data");

if (field != null)
{
field.SetValue(viewControl, data);
}
else
{
throw new Exception("View file: " + path + " does not have a public Data property");
}
}
hf.Controls.Add(viewControl);
pageHolder.Controls.Add(hf);

StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);

return output.ToString();
}
}

//

protected void Button1_Click(object sender, EventArgs e)
{
List<string> obj = new List<string>();
for (int i = 0; i < 10; i++)
obj.Add(i.ToString());
string str = ViewManager.RenderView("UserControls/User.ascx", obj);
Response.Write(str);
}More:http://blog.joycode.com/scottgu/archive/2006/10.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: