ASP.NET MVC – Using a Global Controller Filter to Add Information to the ViewBag

Monday, August 12th, 2019

Using a Global Controller Filter to Add Information to the ViewBag

There are times where you may want to add information to the ViewBag in ASP.NET MVC that should be available to all of the views referenced within certain controllers.  For this situation, you can create a global filter that can be applied at the controller or action specific level to make certain information available to the view via the usage of the ViewBag.

Here's a basic filter example:

public class TestInformationFilter : ActionFilterAttribute
{
    public override void OnActionExceuting(ActionExecutingContext context){
        // Set ViewBag Vars
        context.Controller.ViewBag.UserFirstName = context.Session["FirstName"];
        
        // Complete normal actions
        base.OnActionExecuting(context);
    }
}

Register your global filter by editing the FilterConfig.cs file found in the App_Start folder like so:

public class FilterConfig{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters){
        filters.Add(new TestInformationFilter());
    }
}

Make all views from a controller have access to this ViewBag information by applying the filter to the controller:

[TestInformationFilter]
public class MyController{
   // My controller code here
}