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
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.
If anyone is still looking for a solution to this it appears that you can do it with TempData:
TempData["x"] = x;
TempData is persisted until it is read so you can just read it in your _Layout. You just have to be careful that you read everything so that it is cleared for the next request.
You can do this trick in your partial view to override the title in your _Layout.cshtml:
@{
ViewBag.Title = "About Us From The Partial View";
}
......
<script type="text/javascript">
document.title = "@ViewBag.Title";
</script>
I encountered the same problem when I use mvc3, and I found that
this.ViewBag.ViewBag.PropertyName
works in your custom control.