在.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中文網其他相關文章!