【问题标题】:ASP.NET MVC ActionFilter parameter bindingASP.NET MVC ActionFilter 参数绑定
【发布时间】:2009-12-25 16:11:41
【问题描述】:

如果动作方法中有模型绑定参数,如何在动作过滤器中获取该参数?

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

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

}

有没有办法在不通过 Form 变量的情况下获取 myCar?

【问题讨论】:

标签: asp.net-mvc action-filter


【解决方案1】:

不确定 OnActionExecuted 但您可以在 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
            }
        }
    }
}

【讨论】:

  • 我不认为你可以在那里使用ActionFilter,它是ActionFilterAttribute。另外,您从哪里获得 ActionExecutedContext 上的 ActionParameters 属性?
  • 谢谢,它是 ActionFilterAttribute - 你是对的。我没有注意到这个问题是关于 OnActionExecuted。
  • 谢谢大家。编辑了我原来的问题以说明 ActionFilterAttribute。
  • 很好的答案,但是“if(filterContext.ActionParameters["myCar"] is Car) filterContext.ActionParameters["myCar"] as Car" 好一点。
猜你喜欢
  • 1970-01-01
  • 2010-10-13
  • 2011-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多