ASP.NET Core MVC中,如何将视图文件生成的html代码通过字符串返回
下面的方法可以在ASP.NET Core MVC中,将视图文件生成的html代码通过字符串返回。
首先定义一个静态类ControllerExtensions,里面包含Controller的扩展方法RenderViewAsync,用于返回视图文件生成的html代码:
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 AspNetCore3000ViewGenerator.Models { public static class ControllerExtensions { public static async Task<string> RenderViewAsync(this Controller controller, string viewName, object 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(); } } } }
然后可以在ASP.NET Core MVC的Controller中调用RenderViewAsync方法,返回一个视图文件生成的html代码:
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using AspNetCore3000ViewGenerator.Models; namespace AspNetCore3000ViewGenerator.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public async Task<IActionResult> Index() { this.ViewData["Message"] = "This is a demo message!";//在Controller中设置ViewData的值后,就可以在下面调用RenderViewAsync方法生成视图Index.cshtml的html代码时,在视图Index.cshtml中获取到ViewData的值 string html = await this.RenderViewAsync("Index", null);//获取HomeController下,通过视图Index.cshtml生成的html代码 return View(); } } }
视图Index.cshtml的代码如下:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <h1>Index view!</h1> </div> <div> @ViewData["Message"].ToString()<!--在视图Index.cshtml中,获取ViewData的值--> </div> </body> </html>
参考文献:
Return View as String in .NET Core,特别是这个回复。