我使用以下内容呈现字符串的局部视图…
protected string RenderPartialViewToString(string viewName,object model) { if (string.IsNullOrEmpty(viewName)) viewName = ControllerContext.RouteData.GetrequiredString("action"); ViewData.Model = model; using (var sw = new StringWriter()) { ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,viewName); var viewContext = new ViewContext(ControllerContext,viewResult.View,ViewData,TempData,sw); viewResult.View.Render(viewContext,sw); return sw.GetStringBuilder().ToString(); } }
然而它返回带有如下所示的奇怪标签的html …(我已经包含了一个小部分作为它的大视图)
<$A$><div</$A$><$B$> class="modal hide fade"</$B$><$C$> id="dialog"</$C$><$D$>
整个HTML都会发生这种情况.这部分看起来应该是……
<div class="modal hide fade" id="dialog" style="display: none;">
解决方法
以下代码一直对我有用.虽然我看不出任何重大差异,但却无法完全理解为什么你会得到你得到的输出.
public static String RenderRazorViewToString(ControllerContext controllerContext,String viewName,Object model) { controllerContext.Controller.ViewData.Model = model; using (var sw = new StringWriter()) { var ViewResult = ViewEngines.Engines.FindPartialView(controllerContext,viewName); var ViewContext = new ViewContext(controllerContext,ViewResult.View,controllerContext.Controller.ViewData,controllerContext.Controller.TempData,sw); ViewResult.View.Render(ViewContext,sw); ViewResult.ViewEngine.ReleaseView(controllerContext,ViewResult.View); return sw.GetStringBuilder().ToString(); } }