// 将用户控件转换为字符串
01 public static string RenderPartialToString(string file, object view)
02 {
03 ViewDataDictionary vd = new ViewDataDictionary(view);
04 ViewPage viewPage = new ViewPage { ViewData= vd };
05 Control control = viewPage.LoadControl(file);
06
07 viewPage.Controls.Add(control);
08
09 StringBuilder str = new StringBuilder();
10 using (StringWriter stringWriter = new StringWriter(str))
11 {
12 using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter))
13 {
14 viewPage.RenderControl(htmlTextWriter );
15 }
16 }
17
18 return str.ToString();
19 }
// 调用它
1 public string GetHtmlFromPartial()
2 {
3
4
5
6 string s = RenderPartialToString("~/Views/usercart.ascx", null);
7
8 return s;
9 }
作者:仓储大叔,张占岭,
荣誉:微软MVP