views:

215

answers:

4

I've got some experience with ASP.NET MVC, but only with a web application where the content of the master page doesn't change. I've been wondering how you would handle a site where for example the menu (which is on the master page) is loaded from a database. Where would you load this data?

In WebForms, you would load the menu in the code-behind of the master page, or have the menu as a user control and do the loading in the code-behind of that. But where is this done in MVC?

Do you create a class that inherits from Controller that you use for all your Controllers and let that load the menu on every Action invocation (I don't know if that's possible, but it seems likely)?

Or do you create a utility method that you call in every Action where you want it (because some Actions may only return a partial view that won't reload the menu), which - while not disastrous - seems a little tiresome.

Or would you sin against MVC and just load it in the master page's code-behind?

What's the best approach to this (of course not limited to my solutions)?

+1  A: 

ActionFilters are used to intercept a request and do some processing. You could use them.

Is it a sin against the MVC pattern?

You are breaking the MVC pattern to some extent. But the higher level point is: does it provide much more value if you force yourself not to break it? I don't think that puts you in much trouble, so keep simplicity and maintainability in mind and choose the way you'd do it in your specific situation.

Mehrdad Afshari
A: 

I would create a model type that the master page gets its data from. Then derive the page's model type from the MasterModel.

The controller populates an instance of the PageModel, and the master page picks it up.

(Alternatively the master page's model could be an interface implemented by the pages' models.)

NB. In MVC CTPs doing this required some intermediate classes to override type matching to get to base class data. I don't know if this has been fixed in RTM.

Richard
+1  A: 

this article may help

http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/

jayrdub
A: 

The ASP.NET MVC Futures assembly (more info here) contains an extension method that lets you do this in your master page:

<% Html.RenderAction<NavigationController>(c => c.Show()); %>

You need to reference the assembly and add the "Microsoft.Web.Mvc" namespace in your web.config file for this to work.

David H