2014-10-08 38 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

相關問題