在 .NET Core 中以字符串形式返回视图
问题:
许多可用文章提供有关在 ASP.NET 中将视图渲染为字符串的指南,但并非专门针对 .NET Core。尽管尝试进行转换,.NET Core 实现仍会触发编译错误。
Using 语句:
要解决此问题,需要以下 using 语句:
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;
Project.json依赖项:
对应的project.json依赖项为:
{ "dependencies": { "Microsoft.AspNetCore.Mvc": "1.1.0", ... }, }
控制器扩展方法:
以下扩展方法可以是实现将视图呈现为 .NET 中的字符串核心:
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);
对于部分视图:
partialViewHtml = await this.RenderViewAsync("Report", model, true);
此解决方案为模型提供强类型,当查找视图,异步操作。
以上是如何在 .NET Core 中将视图渲染为字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!