一、.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);}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/8102.html
標籤:ASP.NET
上一篇:NET 判斷是否為回文
