ASP.NET MVC Pass object from Custom Action Filter to Action

The better approach is described by Phil Haack.

Basically this is what you do:

public class AddActionParameterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        // Create integer parameter.
        filterContext.ActionParameters["number"] = 123;

        // Create object parameter.
        filterContext.ActionParameters["person"] = new Person("John", "Smith");
    }
}

The only gotcha is that if you are creating object parameters, then your class (in this case Person) must have a default constructor, otherwise you will get an exception.

Here’s how you’d use the above filter:

[AddActionParameter]
public ActionResult Index(int number, Person person)
{
    // Now you can use number and person variables.
    return View();
}

Leave a Comment