在IView.Render之后存储ViewBag

时间:2015-01-11 21:01:53

标签: c# asp.net-mvc razor

我使用此功能将视图呈现为字符串:

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中更改?

0 个答案:

没有答案