一、.Net Core Mvc下获得

建立一个帮助类,如下:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks; namespace NetCorePortal.Models
{
public class ViewHtmlHelper
{
public static string ConvertToString(Controller controller, string viewName, object viewModel, bool isMainPage)
{
controller.ViewData.Model = viewModel;
using (StringWriter sw = new StringWriter())
{
IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
ViewEngineResult viewEngineResult = viewEngine.FindView(controller.ControllerContext, viewName, isMainPage);
if (viewEngineResult.Success)
{
ViewContext viewContext = new ViewContext(
controller.ControllerContext,
viewEngineResult.View,
controller.ViewData,
controller.TempData,
sw,
new HtmlHelperOptions()
);
viewEngineResult.View.RenderAsync(viewContext);
return sw.GetStringBuilder().ToString();
}
else
{
return $"视图{viewName}不存在";
}
}
}
}
}

后台调用方法

public ContentResult ViewToStringDemo()
{
string strView = ViewHtmlHelper.ConvertToString(this, "Index", "", true);
return Content(strView);
}

参考自:https://www.cjavapy.com/article/147/

二、.Net Mvc下获得

/// <summary>
/// 获得LayTreeGrid视图的HTML内容
/// </summary>
/// <returns></returns>
public ContentResult ViewText()
{
string html = string.Empty;
IView view = ViewEngines.Engines.FindView(this.ControllerContext, "LayTreegrid", null).View; ViewDataDictionary vdd = new ViewDataDictionary();
TempDataDictionary tdd = new TempDataDictionary();
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
ViewContext viewContext = new ViewContext(this.ControllerContext, view, vdd, tdd, sw);
viewContext.View.Render(viewContext, sw);
html = sw.ToString();
}
return Content(html);
}

最新文章

  1. CentOS Mono Nginx 部署 MVC4+WebApi
  2. JavaWeb学习笔记——Tomcat数据源
  3. C语言单向循环链表解决约瑟夫问题
  4. Jackson - Features for configuring Java-to-JSON mapping
  5. VC++创建、调用dll的方法步骤
  6. executeBatch()相关操作汇总
  7. python结巴(jieba)分词
  8. User authentication in Django(用户认证)
  9. C# 往Datatable中添加新行的步骤
  10. 基于window自带功能生成目录树
  11. [原创]STM32 BOOT模式配置以及作用
  12. windows上完美的X-server服务器软件:MobaXterm
  13. PAT甲1031 Hello World for U【字符串】
  14. python 分布式进程体验
  15. 【BZOJ】【4066】简单题(强制在线)
  16. Educational Codeforces Round 11 A. Co-prime Array 水题
  17. 阿里面试题,N个士兵的通话问题
  18. SQL语句创建相同结构的表
  19. zufe 蓝桥选拔
  20. 树莓派(Raspberry Pi 3) - 系统烧录及xshell连接

热门文章

  1. 如何获得大学教材的PDF版本?
  2. Git - Git分支管理策略
  3. Grafana+Prometheus 监控 MySQL
  4. 用Python制作的一本道生成器,最后笑喷了!
  5. Java生鲜电商平台-订单模块状态机架构设计
  6. 剑指offer笔记面试题12----矩阵中的路径
  7. Flutter学习笔记(19)--加载本地图片
  8. iOS---------开发中 weak和assign的区别
  9. cssW3c书写规范
  10. 网络编程~~~osi五层协议