Search code examples
asp.net-mvcaction-filter

ASP.NET MVC ActionFilter parameter binding


If you have a model-bound parameter in an action method, how can you get to that parameter in an action filter?

[MyActionFilter]
public ActionResult Edit(Car myCar)
{
    ...
}

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //I want to access myCar here
    }

}

Is there anyway to get myCar without going through the Form variables?


Solution

  • Not sure about OnActionExecuted but you can do it in OnActionExecuting:

    public class MyActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // I want to access myCar here
    
            if(filterContext.ActionParameters.ContainsKey("myCar"))
            {
                var myCar = filterContext.ActionParameters["myCar"] as Car;
    
                if(myCar != null)
                {
                    // You can access myCar here
                }
            }
        }
    }