zoukankan      html  css  js  c++  java
  • MVC获得某个View 或者 PartialView 生成的字符串

    在开发中有时要在后台获得某个View 或者 PartialView 生成的字符串,只要你熟悉Asp.Net MVC  生命周期就能理解和敲出下面的代码。没什么高深的,直接上代码:

    1,输出View HTML 字符串:
     

            /// <summary>
            /// 描述:输出View HTML 字符串
            /// </summary>
            /// <param name="controller"></param>
            /// <param name="viewName">视图文件名</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 HTML 字符串:

            /// <summary>
            /// 描述:输出PartialView HTML 字符串
            /// </summary>
            /// <param name="controller"></param>
            /// <param name="partialViewName">部分视图文件名</param>
            /// <returns></returns>
            protected static string RenderPartialViewToString(Controller controller, string partialViewName)
            {
                IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).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();
                }
            }

  • 相关阅读:
    TransmitFile
    xml
    鼠标划过表格行变色-简洁实现
    关于表变量
    显式接口成员实现
    华为致新员工书
    C#实现的堆栈
    Gridview中合并单元格,某字段的内容相同时如何只显示一个,屏蔽相同列或行的内容(转)
    ASP.NET 验证控件
    动态SQL EXEC
  • 原文地址:https://www.cnblogs.com/bober/p/2334266.html
Copyright © 2011-2022 走看看