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

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
}

Rent dedicated game servers from Chicago, Kansas City, Dallas Texas, Wilkes-Barre Pennsylvania, Arizona, Denver Colorado, California, Florida, and Sofia Bulgaria starting as low as $7.45 a month. We Be HostiN (https://webehostin.com)

Tags: , , , , , , , , ,

Leave a Reply

You must be logged in to post a comment.