views:

45

answers:

2

I wonder - what is the best way to supply contextual (i.e. not related to any particular view, but to all views at the same time) info to a view (or to master page)?

Consider the following scenario.

Suppose we have an app that supports multiple UI languages. User can switch them via UI's widgets (something like tabs at the top of the page). Each language is rendered as a separate tab. Tab for the current language should not be rendered.

To address these requirements I'm planning to have a javascript piece that will hide current's language tab on the client. To do this, I need current's language tab Id on the client. So, I need some way of passing the Id to master page (for it to be 'fused' into the js script).

The best thing I can think of is that all my ViewModels should inherit some ViewModeBase that has a field to hold current language tab Id. Then, whatever View I'm rendering, this Id will always be available for the master page's hiding script.

However, I'm concerned that this ViewModelBase can potentially grow in an uncontrolled fashion as number of such pieces of contextual info (like current language) will grow..

Any ideas?

+1  A: 

If this contextual information is needed by all views then having a base view model seems like a good solution. The question is where to populate this information to avoid cluttering all your controller actions. A custom action filter seems like a good place. In the OnActionExecuted method you could get the view model returned by the controller action and populate the contextual part if it derives from the base type.

Another option is to put the contextual information into the ViewData (strongly typed views can also use ViewData) but personally I hate having magic strings and doing casting in my views (this could be overcome by using HTML helpers that will handle this ViewData).

Darin Dimitrov
Thanks for the answer!To avoid clutter in controllers, I create my view models thru a factory. So, the factory is in charge of filling ViewModelBase's properties.
Andrey
A: 

If you think that ViewModeBase will grow to much you can also have viewmodels implement an interface.

The View or Partial can have the type of that interface. Thats especially usefull if only some pages have that functonality.

Malcolm Frexner
I see your point. Thanks.But I just have a gut feeling that there is a better solution out there :)Besides, I dont rememeber exactly who, but somebody from MVC team I guess commented in a blog that having ViewModelBase for those purposes is not a good thing..
Andrey