问题描述
看来,将视图呈现为字符串的大多数代码在 MVC 5 中都不起作用.
It seems, most code for rendering view into string doesn't work in MVC 5.
我有最新的 MVC 5.1.2 模板,我正在尝试将视图呈现为字符串.
I have latest MVC 5.1.2 templates and I am trying to render view into string.
public static String RenderViewToString(ControllerContext context, String viewPath, object model = null)
{
context.Controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindView(context, viewPath, null);
var viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(context, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
好吧,它正在工作,但它的输出包含很多 $ 标记而不是标签.我读到一些关于它的内容已在 RC 版本中修复,但这是旧新闻.
Well, it's working but its output contains lots of $ marks instead tags. I read something about it was fixed in RC version, but that's old news.
问题看起来像这样
<$A$><h1></h1>
<table</$A$><$B$> class=""</$B$><$C$>> <tbody</$C$><$D$></$D$><$E$>></tbody>
</table></$E$>
我想问一下,你如何在最新的 MVC 5 模板中将视图渲染成字符串?谢谢.
I would like to ask, how do you render views into string in latest MVC 5 template ?Thanks.
推荐答案
好的,我似乎找到了解决方案.这个想法的作者是亚基尔庄园.
Ok, seems I found a solution. Author of the idea is Yakir Manor.
class FakeController : ControllerBase
{
protected override void ExecuteCore() { }
public static string RenderViewToString(string controllerName, string viewName, object viewData)
{
using (var writer = new StringWriter())
{
var routeData = new RouteData();
routeData.Values.Add("controller", controllerName);
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://google.com", null), new HttpResponse(null))), routeData, new FakeController());
var razorViewEngine = new RazorViewEngine();
var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);
var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
razorViewResult.View.Render(viewContext, writer);
return writer.ToString();
}
}
}
这是一个带有虚假上下文和响应的技巧.
It's a trick with fake context and response.
示例:
String renderedHTML = RenderViewToString("Email", "MyHTMLView", myModel );
我的文件 MyHTMLView.cshtml 存储在 Views/Email/MyHTMLView.cshtml 中.电子邮件是虚假的控制器名称.
My file MyHTMLView.cshtml is stored in Views/Email/MyHTMLView.cshtml. Email is a fake controller name.
这篇关于MVC 5 将视图渲染为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!