使用控制器扩展在 .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中文网其他相关文章!