简体   繁体   中英

Is there a way to pass (or access) a controller's ModelState to an ActionFilterAttribute?

I have a custom validation attribute derived from action filter attribute. Currently the attribute simply sets an ActionParameter value indicating if the item validated was good or not and then the action has to have logic to determine what to do with information.

 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
 }

I would like to perform a ModelState.AddModelError() while in the attribute's OnActionExecuting() method which would save me having the controller perform this logic.

I've tried adding a ModelState property to attribute but this data does not appear to be available to pass into the attribute.

Is there a way to gain access to the ModelState from within the attribute?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM