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?
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.
I believe the core to your concerns would best be served by using Sections.
http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx
You can define sections and then update them with
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:
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