views:

272

answers:

5

Is there a good way to assign ViewData to nested master pages? For example, in my top level masterpage I might have info on the logged in user. I also have a nested masterpage that is displayed when the user is on any departmental page. I want that data available ONLY on departmental pages.

So this is how it looks:

Top Level Master Page - Includes ViewData["userData"]
    |
    |
    ---> Nested Master Page - Includes ViewData["departmentalData"]

So whenever I have a view that uses the nested master page it would include both ViewData["userData"] and ViewData["departmentalData"]. But if I am only using the top level master page then I only have ViewData["userData"]. Is this possible?

A: 

One possibility is to write an extension method on both ViewPage and ViewMasterPage to get the data you need. I'm not sure, but I think this is what Rob Conery did in his Commerce.MVC package. Take a look at that.

Stuart Branham
+1  A: 

If you insist on using ViewData as the data-carrier to the master pages (instead of using Html.RenderAction(...) from the MvcContrib project which I probably would use) then if you can identify in which cases the nested masterpage will be used, you can setup an ActionFilter to input the needed data into ViewData["departmentalData"].

AndreasKnudsen
A: 

We had the same problem. So far we came up with a base class for all controllers and a protected method to generate the ViewData. We call it from all actions that use this specific master page.

I'll definitely follow this question to see what others have come up with.

chris166
A: 

There is a concept of subcontrollers for MVC (I am not sure if this is still present and will make its way in the MVC framework). You can find it in the mvc contrib project on codeplex. Some description or blog post can be found here...

http://mhinze.com/subcontrollers-in-aspnet-mvc/

and passing objects to that subcontroller is discussed here...

http://mhinze.com/passing-objects-to-subcontrollers/

This is not based on masterpages but could help you...

silverfighter
A: 

As long as your controller is setting the proper ViewData for the page that will be viewed then it shouldnt matter how many master pages are being used. Or am I missing something?

Tony Borf