使用控制器擴充功能在.NET Core 中將視圖渲染為字串
本文旨在協助您將渲染視圖的現有程式碼轉換為ASP.NET 中的字串與.NET Core 無縫協作。
提供的程式碼假設有一個 Controller 方法呼叫RenderViewToString 方法。但在適配.NET Core時,可能會遇到編譯錯誤。本文介紹了專為 .NET Core 設計的程式碼的修改版本。
修改後的程式碼:
以下程式碼片段提供了 RenderViewToString方法的增強版本:控制器副檔名:
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewFeatures; using System.IO; using System.Threading.Tasks; namespace CC.Web.Helpers { public static class ControllerExtensions { public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false) { if (string.IsNullOrEmpty(viewName)) { viewName = controller.ControllerContext.ActionDescriptor.ActionName; } controller.ViewData.Model = model; using (var writer = new StringWriter()) { IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine; ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial); if (viewResult.Success == false) { return $"A view with the name {viewName} could not be found"; } ViewContext viewContext = new ViewContext( controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions() ); await viewResult.View.RenderAsync(viewContext); return writer.GetStringBuilder().ToString(); } } } }
用法:
您可以使用更新的程式碼,語法如下:
viewHtml = await this.RenderViewAsync("Report", model);
用於渲染PartialView:
partialViewHtml = await this.RenderViewAsync("Report", model, true);
注意:
以上是如何在 .NET Core 控制器中將視圖渲染為字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!