Site icon Ryadel

ASP.NET MVC: How to set global ViewBag properties and have them available in each View

When you're building a website featuring a whole lot of Views you most likely end up setting a lot of variables & properties in each and every ViewBag object: some common examples are stuff like IsAdmin, IsAuthenticated, AvatarURL and similar tropes. When such situation arises, in order to avoid to cut & paste the exact same bunch of code in each and every controller method, it's highly advisable to get the job done in a more convenient (i.e. centralized) way. The most widely-used approaches to fullfill this task are the following:

 

1. The Base Class.

PROS: Quite simple to implement, few lines of code, highly reusable. It can also be opted-out at will (thanks to Frank V. E. for pointing it out in this StackOverflow thread).
CONS: Being forced to derive all your controllers from a base class might have some impact, especially if you have a lot of controllers already in place and/or you need to derive them from other base classes.

 

2. The Module.

PROS: None I'm aware of.
CONS: None I'm aware of (except  being a bit counterintuitive).

 

3. The RegisterController hook.

PROS: Fast, secure, reusable: ideal for any IoC design pattern.
CONS: Not always suited for small project and/or simple websites: if you're not using IoC you're often not using RegisterController at all.

 

4. The Global (.asax) ActionFilter.

PROS: Easily the less-obtrusive method amongst those mentioned.
CONS: None I'm aware of.

Like (almost) always there isn't really a best choice here, it mostly depends on your project settings and your developer needs. That being said, my preference goes towards the latter for the aforementioned reasons.

And yours?

Exit mobile version