Nullius
Nullius

Reputation: 2702

MVC4 Site Options

Where or how exactly do you pass configuration settings (stored in a database) to your views?

Let's say a user can set different settings in his profile. These options should be available in every view and partial view.

Some options:

And where would you put the logic to obtain the information? I'd like to avoid calling a method in each and every action (using a custom base controller maybe?)

I've tried searching 'mvc options', 'global variables mvc', 'viewbag mvc', 'configuration mvc', ... Nothing relevant came up. I'm probably just using the wrong search keywords.

Thanks!

Upvotes: 1

Views: 64

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039000

  • Global static variables - Bad practice

Not only it's bad practice but they are shared among all users. In your case you need per-user information

  • Viewbag?

Weakly typed collection relying on magic strings, bad practice. I don't like it nor would ever use it.

  • Wrapper class that contains the 'actual' model and a 'configuration' model.

Yes, you could use a common base view model for all your views that will contain the Settings property.

And where would you put the logic to obtain the information?

One possibility would be to have a global action filter that will execute after each action, retrieve the model passed to the view and since all your models will derive from a common base view model, query the database and assign a value to the settings property.

There's also another approach you might consider. You mentioned that you need this information in every view. Instead of having a common base view model you could write a custom HTML helper that will retrieve this information from the database and return it. Of course to avoid multiple roundtrips to the database you could cache the retrieved user settings into the HttpContext.Items.

Upvotes: 3

Related Questions