Asp.Net MVC 在后台获取PartialView、View文件生成的字符串

注:尊重他人原创,转载请务必注明来自http://www.cnblogs.com/Raoh/archive/2013/03/06/2947008.html

在Asp.net MVC的开发中,有时需要在后台代码中获取某个View 或者 PartialView 生成的字符串,简单封装了两个方法如下如下,希望对你有一定的帮助:

1. 将View文件输出为字符串:

      /// <summary>
         /// 将View输出为字符串
         /// </summary>
         /// <param name="controller">Controller实例</param>
         /// <param name="viewName">如果view文件在当前Controller目录下,则直接输入文件名(例:Toolbar);否则,从根路径开始指定(例:~/Views/User/Toolbar.cshtml)</param>
         /// <param name="masterName">母板页文件名</param>
         /// <returns>字符串</returns>
         public static string RenderViewToString(Controller controller, string viewName, string masterName)
         {
             IView view = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, masterName).View;
             using (StringWriter writer = new StringWriter())
             {
                 ViewContext viewContext = new ViewContext(controller.ControllerContext, view, controller.ViewData, controller.TempData, writer);
                 viewContext.View.Render(viewContext, writer);
                 return writer.ToString();
             }
         }


2.将PartialView文件输出为字符串

 1      /// <summary>
 2         /// 将PartialView输出为字符串
 3         /// </summary>
 4         /// <param name="controller">Controller实例</param>
 5         /// <param name="viewName">如果PartialView文件在当前Controller目录下,则直接输入文件名(例:Toolbar);否则,从根路径开始指定(例:~/Views/User/Toolbar.cshtml)</param>
 6         /// <param name="model">构造页面所需的的实体参数</param>
 7         /// <returns>字符串</returns>
 8         public static string RenderPartialViewToString(Controller controller, string viewName,object model)
 9         {
10             IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName).View;
11             controller.ViewData.Model = model;
12             using (StringWriter writer = new StringWriter())
13             {
14                 ViewContext viewContext = new ViewContext(controller.ControllerContext, view, controller.ViewData, controller.TempData, writer);
15                 viewContext.View.Render(viewContext, writer);
16                 return writer.ToString();
17             }
18         } 

 注:尊重他人原创,转载请务必注明来自http://www.cnblogs.com/Raoh/archive/2013/03/06/2947008.html

posted @ 2013-03-06 21:47  大悟飞天  阅读(1634)  评论(2编辑  收藏  举报