15

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?

1

1 Answer 1

12

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
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I don't think you can use ActionFilter there, it is ActionFilterAttribute. Also where did you get the ActionParameters property on the ActionExecutedContext?
Thanks, it is ActionFilterAttribute - you are right. I have not noticed that the question is about OnActionExecuted.
Thanks guys. Edited my original question to state ActionFilterAttribute.
Great answer however "if(filterContext.ActionParameters["myCar"] is Car) filterContext.ActionParameters["myCar"] as Car" is a little better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.