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

后端 未结 4 2074
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 20:14

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

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    Detached         


        
4条回答
  •  生来不讨喜
    2020-11-30 21:04

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

提交回复
热议问题