MVC 5渲染视图为String [英] MVC 5 Render View to String
问题描述
看来,最code渲染视图到字符串中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.cstml存储在查看/电子邮件/ MyHTMLView.cshtml。电子邮件是假的控制器名称。
My file MyHTMLView.cstml is stored in Views/Email/MyHTMLView.cshtml. Email is a fake controller name.
这篇关于MVC 5渲染视图为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!