// 将用户控件转换为字符串
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 }
本文转自博客园张占岭(仓储大叔)的博客,原文链接:MVC如何将用户控件(分部视图,RenderPartial,ViewUserControl)内容转换为字符串并输出,如需转载请自行联系原博主。
时间: 2024-09-22 19:28:16