Modifying MVC 3 ViewBag in a partial view does not

2019-01-17 05:59发布

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 example, when you setup a default ASP.NET MVC 3 project you get a _Layout.cshtml file in the "/Views/Shared" folder. In that _Layout.cshtml the Page Title is set like this:

<title>@ViewBag.PageTitle</title>

Then in "/Views/Home/About.cshtml" view the contents of the ViewBag are modified:

@{
    ViewBag.Title = "About Us";
}

This works fine. When the About view is rendered the page title is "About Us". So, now I want to render a Partial view inside my About view and I want to modify the ViewBag.Title inside my Partial view. ("/Views/Shared/SomePartial.cshtml")

@Html.Partial("SomePartial")

In this Partial view I have this code:

@{
    ViewBag.Title = "About Us From The Partial View";
}

When I debug this code I see the ViewBag.Title get set to "About Us" and then in the Partial view I see it get reset to "About Us From The Partial View", but when the code hits the _Layout.cshtml it goes back to "About Us".

Does this mean that if the contents of the ViewBag are modified in a Partial view, those changes will not appear(be accessible) in the main view (About.cshtml) or the _Layout.cshtml?

Thanks in advance!

10条回答
相关推荐>>
2楼-- · 2019-01-17 06:19

I encountered the same problem when I use mvc3, and I found that

this.ViewBag.ViewBag.PropertyName 

works in your custom control.

查看更多
姐就是有狂的资本
3楼-- · 2019-01-17 06:23

I've tried the following and it works:

In the (parent) view...

@Html.Partial("SomePartial", ViewData, null)

Note: ViewData is passed as the model argument, but you have to specify null for the viewData argument to use the correct overload. You can't use ViewBag because Html.Partial doesn't like dynamics.

Then , in the partial view...

@model ViewDataDictionary
@{
    Model["Title"] = "About us from the partial view";
}

Of course, if you need to use the model argument for a real model, you'll have to be more creative.

查看更多
Anthone
4楼-- · 2019-01-17 06:24

The partial view gets its own ViewBag.

You can get the page's ViewBag from ((WebViewPage) WebPageContext.Current.Page).ViewBag

查看更多
三岁会撩人
5楼-- · 2019-01-17 06:25

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.

查看更多
登录 后发表回答