Modifying MVC 3 ViewBag in a partial view does not persist to the _Layout.cshtml

后端 未结 10 1846

I am using MVC 3 with the Razor view engine. I want to set some values in the ViewBag inside a Partial View and want retrieve those values in my _Layout.cshtml. For exampl

10条回答
  •  隐瞒了意图╮
    2020-12-08 14:03

    As others have pointed out Layout, Views and Partials get their own ViewBag. However, I was able to get it to work with the following: In the View or Partial.

    @{ Html.ViewContext.ViewBag.Title = "Reusable Global Variable"; }
    

    Then in _Layout

    @Html.ViewContext.ViewBag.Title

    By explicitly using the ViewContext, the views 're-use' the same ViewBag.

提交回复
热议问题