MVC如何将用户控件(分部视图,RenderPartial,ViewUserControl)内容转换为字符串并输出

 

// 将用户控件转换为字符串
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    }
posted @ 2011-08-19 12:23  张占岭  阅读(1621)  评论(2编辑  收藏  举报