Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 layout ViewBag data across all child views

We need dynamic data passed to our layout file, no matter what the child view is. For example, we display some user specific data in the header of the layout.

How can we pass this data to the layout view without each action having to supply it independently? Should we use a custom controller, or is there a better solution?

like image 596
Shane N Avatar asked Mar 05 '11 22:03

Shane N


3 Answers

The strategy that I use is to have a base view model from which all of my view models derive. I use a base controller, though you could also use a global filter, and override OnActionExecuted. When I detect an action that returns a ViewResult, I cast the model to my base view model and set the common properties on the model from the base controller.

The choice between a global filter and a base controller depends on a variety of factors. If it really applies to all actions (that return view results) and you don't need injection to get access to some resources, then I'd probably go with the filter. If you need to have dependencies injected or you have some controllers where the data would be applied and others where it wouldn't (say the Admin controller), then I'd go the base controller route. You will need to remember to derive from the controller if you go with it.

You could also do the same thing with the ViewBag if you don't want to derive from a common view model. I like having the strongly-typed model, but YMMV.

like image 102
tvanfosson Avatar answered Oct 21 '22 04:10

tvanfosson


You could use @Html.Action("ActionName", "ControllerName") in Your _layout file.

Here is article about this: http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx

like image 23
EKOlog Avatar answered Oct 21 '22 04:10

EKOlog


Take a look at the login controls that are standard in a Razor project - these partial views access user data - probably exactly like you'd like to.

e.g. a typical LogonPartial.cshtml might contain:

@if(Request.IsAuthenticated) {
    <text>Welcome <b>@Context.User.Identity.Name</b>!
    [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
    @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}
like image 2
Stuart Avatar answered Oct 21 '22 03:10

Stuart