看来,用于将视图呈现到字符串中的大多数代码在MVC 5中不起作用.
我有最新的MVC 5.1.2模板,我试图渲染视图到字符串.
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版本,但这是旧消息.
问题看起来像这样
<$A$><h1></h1> <table</$A$><$B$> class=""</$B$><$C$>> <tbody</$C$><$D$></$D$><$E$>></tbody> </table></$E$>
我想问一下,如何在最新的MVC 5模板中将视图呈现为字符串?
谢谢.
解决方法
好的,似乎我找到了一个解决方案.这个想法的作者是雅基尔庄园.
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(); } } }
这是一个假的上下文和回应的伎俩.
例:
String renderedHTML = RenderViewToString("Email","MyHTMLView",myModel );
我的文件MyHTMLView.cstml存储在Views / Email / MyHTMLView.cshtml中.电子邮件是一个假控制器名称.