我使用此功能将视图呈现为字符串:
protected virtual string RenderViewToString(string viewName, object model)
{
ViewData.Model = model;
if (viewName == null)
viewName = ControllerContext.RouteData.GetRequiredString("action");
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
在我看来,我设置了一些ViewBag变量(例如标题),如:
@{ ViewBag.Title = "Some title"; }
但viewContext.ViewBag
为空,例如
viewResult.View.Render(viewContext, sw);
var title = viewContext.ViewBag.Title; // null
如何在视图ViewBag
中更改?