zoukankan      html  css  js  c++  java
  • 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"><!-- google_ad_client = "ca-pub-1944176156128447"; /* cnblogs 首页横幅 */ google_ad_slot = "5419468456"; google_ad_width = 728; google_ad_height = 90; //--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

  • 相关阅读:
    总体和样本
    素数和合数
    Scrum 体验活动笔记
    敏捷 扑克上的时间估算(转)
    Python爬取拉勾网职位
    无头浏览器Chromedriver、Phantomjs安装及教程、Chrome插件xpath下载及安装
    Python爬取智联招聘职位信息
    MATLAB 信号与系统
    Python爬虫学习(2)- Ajax的Get、Post方法实战
    Python爬虫学习(1)
  • 原文地址:https://www.cnblogs.com/zcm123/p/6076486.html
Copyright © 2011-2022 走看看