View.Render后如何访问ViewData / ViewBag?

时间:2018-08-02 11:20:03

标签: asp.net-mvc view

我认为这是

@{
    ViewBag.Title = "Page Title";
    ViewBag.Subtitle = "Page Subtitle";
}

然后我用它通过ajax渲染页面(局部视图):

public ActionResult PageView(string pageName = null, object model = null)
{
    if (Request.IsAjaxRequest())
    {
        // return PartialView(pageName, model);
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, pageName);
        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            // Here ViewBag/ViewData does not have the data added by view

            Response.Headers["ex-page-title"] = ViewBag.Title ?? "Title Missing!";
            Response.Headers["ex-page-subtitle"] = ViewBag.Subtitle ?? "Subtitle Missing!";

            return new ContentResult()
            {
                Content = sw.GetStringBuilder().ToString()
            };
        }
    }
    else
    {
        return View(pageName, model);
    }
}

我无法弄清楚如何获取由视图更改的ViewBag的内容。这可能吗?该视图使用的ViewBag是否仅对视图可见,或者在调用Render后应该可用?在我来说,ViewBag / ViewData在View.Render之后始终为空。

2 个答案:

答案 0 :(得分:1)

渲染视图时,会克隆

ViewBag和ViewData。因此,无法在视图内部对其进行任何修改。

如果要访问视图内的数据集,最好的方法是使用模型。您可以在视图内设置模型的某些属性,并且在呈现视图时可以访问它们。

另一种选择是使用不像ViewData和ViewBag一样克隆的TempData。

Response.Headers["ex-page-title"] = TempData["Title"] ?? "Title Missing!";
Response.Headers["ex-page-subtitle"] = TempData["Subtitle"] ?? "Subtitle Missing!";

并在视图内:

@{
    TempData["Title"] = "My page";
    TempData["Subtile"] = "has a title";
}

答案 1 :(得分:0)

您应该创建一个类来保存呈现局部视图所需的所有数据:

public class PageViewModel
{
    public string PageName { get; set; }
    public string Title { get; set; }
    public string Subtitle { get; set; }
    public object Model { get; set; }
}

然后您像这样使用它:

public ActionResult PageView(PageViewModel model = null)
{
    if (Request.IsAjaxRequest())
    {
        // return PartialView(model.PageName, model.Model);
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, model.PageName);
        ViewData.Model = model.Model;

        using (StringWriter sw = new StringWriter())
        {
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            // Here ViewBag/ViewData does not have the data added by view

            Response.Headers["ex-page-title"] = model.Title ?? "Title Missing!";
            Response.Headers["ex-page-subtitle"] = model.Subtitle ?? "Subtitle Missing!";

            return new ContentResult()
            {
                Content = sw.GetStringBuilder().ToString()
            };
        }
    }
    else
    {
        return View(model.PageName, model.Model);
    }
}

然后,当您通过ajax呈现此页面视图时,只需设置适当的属性即可。