【问题标题】:Check ModelState in action filter检查动作过滤器中的 ModelState
【发布时间】:2011-11-17 08:40:29
【问题描述】:

我可以在OnActionExecuting 方法中的自定义操作过滤器中检查ModelState.IsValid 吗?

【问题讨论】:

    标签: asp.net-mvc-3 action-filter modelstate


    【解决方案1】:

    是的。 ModelState 是 ViewData 的一部分。所以你可以使用:

    filterContext.Controller.ViewData.ModelState
    

    例如,如果你想在动作执行后注入一些代码,但前提是ModelState.IsValid == true,你可以这样做:

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (!filterContext.Controller.ViewData.ModelState.IsValid) return;
        // do something
    }
    

    【讨论】:

    • 哇,谢谢...有趣的是,缺少像 ModelState 这样简单的东西是 ViewData 的一部分会如此烦人。这也适用于视图!
    • 会的,如果不是视图,ViewData 什么都不是。
    猜你喜欢
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2016-06-20
    相关资源
    最近更新 更多