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

在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>
         protected 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         } 

 


<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值