2014-10-08 78 views
0

我在下面的操作过滤器本身中修改了ActionType,但仍然出现了模型状态错误,因为“该字段ActionType必须匹配正则表达式'1 | 2 | 3 | 4' “。ModelState即使在修改属性的操作时也会出现错误

对于我的模型属性为

[RegularExpression("1|2|3|4")] 

public int ActionType { get; set; } 

我的操作类型ENUM是

public enum ActionType 
     { 
      Add = 1, 
      Update = 2, 
      Delete = 3, 
      Search = 4 
     } 

行动过滤器是

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) 
     { 
      var formData = actionContext.ActionArguments.FirstOrDefault().Value as EntityBase; 
      if (formData != null) 
      { 
       string methodType = actionContext.Request.Method.Method; 
       switch (methodType.ToUpper()) 
       { 
        case "POST": 
         formData.ActionType = (int)ActionType.Add; 
         break; 
        case "PUT": 
         formData.ActionType = (int)ActionType.Update; 
         break; 
        case "DELETE": 
         formData.ActionType = (int)ActionType.Delete; 
         break; 
        case "GET": 
         formData.ActionType = (int)ActionType.Search; 
         break; 
        // Your errors 
       } 
      } 
      base.OnActionExecuting(actionContext); 
     } 
+0

模型绑定和验证发生之前** **行动过滤器被解雇 – 2014-10-08 22:02:13

+0

嗨@Stephen请您建议我到什么地方做到这一点? – 2014-10-09 08:52:01

+1

您可以创建一个自定义模型绑定器来防止添加验证错误或(可能更容易,但我没有测试过)访问'actionContext.ModelState'属性并清除错误 - if(actionContext.ModelState.ContainsKey(“ ActionType“)){actionContext.ModelState [”ActionType“] .Errors.Clear(); }'但是为什么如果你总是将它设置在动作过滤器中,那么为属性添加验证属性呢? – 2014-10-09 09:16:54

回答

0

你可以改变操作类型属性的数据标注使用范围,而不是RegularExpression ??

[Range(1, 4)] 
public int ActionType { get; set; } 
+0

嗨@Krishna Teja,这不能解决我的问题,我已经采取你的建议,并会做出改变 – 2014-10-09 08:52:51

相关问题