我找到了一些文章如何在 ASP.NET 中将 View 返回到字符串,但无法隐藏任何内容以使用 .NET Core 运行它
public static string RenderViewToString(this Controller controller, string viewName, object model)
{
var context = controller.ControllerContext;
if (string.IsNullOrEmpty(viewName))
viewName = context.RouteData.GetRequiredString("action");
var viewData = new ViewDataDictionary(model);
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
假设能够从 Controller 调用:
var strView = this.RenderViewToString("YourViewName", yourModel);
当我尝试将上述代码运行到 .NET Core 中时,我遇到了很多编译错误。
我试图将它转换为与 .NET Core 一起使用,但失败了,任何人都可以帮助提及所需的 using ..
和所需的 “dependencies”:{
"Microsoft.AspNetCore.Mvc": "1.1.0",
...
},
在 project.json
中使用。
注意
我需要将 View 转换为 .NET Core 中的 string
的解决方案,无论是否转换了相同的代码,或者可以通过其他方式转换。
最佳答案
如果像我一样,您有许多需要此功能的 Controller ,例如在报告站点中,重复此代码并不是很理想,甚至注入(inject)或调用其他服务似乎也不正确。
所以我制作了我自己的上述版本,但有以下不同之处:
- 模型强类型
- 查找 View 时的错误检查
- 能够将 View 呈现为局部 View 或页面
- 异步
- 作为 Controller 扩展实现
不需要 DI
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);
关于c# - 在 .NET Core 中以字符串形式返回 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40912375/