开发者

Passing contextual info to Views in ASP.NET MVC

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?


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜