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

reach4thelasers picture reach4thelasers · Nov 27, 2009 · Viewed 39.7k times · Source

If I create an object in a Custom Action Filter in ASP.NET MVC in

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    DetachedCriteria criteria = DetachedCriteria.For<Person>();
    criteria.Add("stuff");

    // Now I need to access 'criteria' from the Action.....

}

is there any way I can access the object from the Action that is currently executing.

Answer

niaher picture niaher · Nov 28, 2012

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();
}