Passing contextual information to views in ASP.NET MVC

I wonder what is the best way to provide contextual (i.e. not related to any particular view, but to all views at the same time) information to the view (or to the main page)?

Consider the following scenario.

Suppose we have an application that supports several interface languages. The user can switch them through the widgets of the user interface (something like tabs at the top of the page). Each language is displayed as a separate tab. A tab for the current language should not be displayed.

To solve these requirements, I plan to have a javascript part that will hide the current language tab on the client. To do this, I need the current identifier of the language command on the client. So, I need to somehow pass the Id to the main page (so that it "merges" with the js script).

The best I can come up with is that all my ViewModels should inherit some ViewModeBase, which has a field to store the current language tab Id. Then, no matter what is displayed in view I, this identifier will always be available for the main page hiding the script.

However, I am concerned that this ViewModelBase could potentially grow unchecked, as the number of such pieces of contextual information (such as the current language) will grow.

Any ideas?

+4
source share
2 answers

If all the views need this contextual information, then having a basic presentation model seems like a good solution. The question is where to fill in this information so as not to clutter up all the actions of your controller. A custom action filter seems like a good place. In the OnActionExecuted method , you can get the view model returned by the controller action and fill in the contextual part if it is obtained from the base type.

Another option is to place contextual information in ViewData (strongly typed views can also use ViewData), but personally I hate having magic lines and casting in my views (this can be overcome with the help of HTML helpers that will process this ViewData).

+1
source

If you think that ViewModeBase will grow, you can also use viewmodels to implement the interface.

View or Partial may have a type of this interface. This is especially useful if only some pages have this functionality.

0
source

Source: https://habr.com/ru/post/1310825/


All Articles