Search code examples
c#asp.netasp.net-mvcaction-filteractionfilterattribute

How do I pass a variable from an ActionFilter to a Controller Action in C# MVC?


Taking a simple action filter, which checks if the user is logged in and retrieves their user ID.

public class LoginFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {    
        // Authenticate (somehow) and retrieve the ID
        int id = Authentication.SomeMethod();
        // Pass the ID through to the controller?
        .....
    }
}

How could I then pass this ID through to my controller action?

[LoginFilter]
public class Dashboard : Controller
{
    public ActionResult Index()
    {
        // I'd like to be able to use the ID from the LoginFilter here
        int id = ....
    }
}

Is there an equivalent to the ViewBag that would allow me to do this? Or some other technique that allows me to pass variables and objects between the filter and the controller action?


Solution

  • You can use ViewData/ViewBag like this:

    1.) Using ViewData

    NOTE: In case of ViewData you need to do one step that is you have to typecast it

    public class LoginFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {    
            // Authenticate (somehow) and retrieve the ID
            int idValue = Authentication.SomeMethod();
    
            // Pass the ID through to the controller?
            filterContext.Controller.ViewData.Add("Id", idValue);
        }
    }
    

    And then in Controller function

    [LoginFilter]
    public class Dashboard : Controller
    {
        public ActionResult Index()
        {
            // I'd like to be able to use the ID from the LoginFilter here
            int id = (int)ViewData["Id"];
        }
    }
    

    2.) Using ViewBag

    public class LoginFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {    
            // Authenticate (somehow) and retrieve the ID
            int idValue = Authentication.SomeMethod();
    
            // Pass the ID through to the controller?
    
            filterContext.Controller.ViewBag.Id = idValue; 
        }
    }
    

    And then in controller

    [LoginFilter]
    public class Dashboard : Controller
    {
        public ActionResult Index()
        {
            // I'd like to be able to use the ID from the LoginFilter here
            int id = ViewBag.Id;
        }
    }