【问题标题】:Is there a way to pass (or access) a controller's ModelState to an ActionFilterAttribute?有没有办法将控制器的 ModelState 传递(或访问)到 ActionFilterAttribute?
【发布时间】:2010-11-07 16:08:02
【问题描述】:

我有一个从动作过滤器属性派生的自定义验证属性。目前,该属性仅设置一个 ActionParameter 值,指示验证的项目是否良好,然后该操作必须具有确定如何处理信息的逻辑。

 public class SpecialValidatorAttribute: ActionFilterAttribute
 {
     public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
          // ... valdiation work done here ...
          filterContext.ActionParameters["SpecialIsValid"] = resultOfWork;

          base.OnActionExecuting(filterContext);
     }
 }

 [SpecialValidator]
 public ActionResult Index(FormCollection collection, bool SpecialIsValid)
 {
     if(!SpecialIsValid)
         // add a modelstate error here ...

     // ... more stuff
 }

我想在属性的 OnActionExecuting() 方法中执行 ModelState.AddModelError(),这样可以让控制器执行此逻辑。

我尝试将 ModelState 属性添加到属性,但此数据似乎无法传递给属性。

有没有办法从属性中获取对 ModelState 的访问权限?

【问题讨论】:

    标签: c# asp.net-mvc attributes


    【解决方案1】:

    假设您的控制器类派生自 System.Web.Mvc.Controller(可能就是这种情况),您可以试试这个:

    ((Controller)filterContext.Controller).ModelState.AddModelError("key", "value");
    

    【讨论】:

    • 呸!我之前尝试过这个时没想过要投射它。谢谢。
    猜你喜欢
    • 2021-12-28
    • 2018-02-09
    • 2023-02-18
    • 2020-03-02
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多