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?

About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

4 Comments on “ASP.NET MVC: How to set global ViewBag properties and have them available in each View”

  1. This list of possible methods with theirs pros and cons helped me a lot. Thanks for a great article!

  2. Thanks for the article. But I have a question. How is the value happening?
    this.ViewBag.MyProperty = “value”;

    1. I don’t understand your question. If you want to know how you can use that value in your View, it’s just as simple as typing @ViewBag.MyProperty (assuming it’s a string): otherwise, you have to cast it, such as @((YourClass)ViewBag.MyProperty).SomeProperty instead.

Leave a Reply

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.