2009-07-02 55 views
4

我有一個從操作過濾器屬性派生的自定義驗證屬性。目前,該屬性只是設置一個ActionParameter值,該值指示驗證的項目是否良好,然後該操作必須具有邏輯以確定如何處理信息。有沒有辦法將控制器的ModelState傳遞(或訪問)到ActionFilterAttribute?

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 
} 

我想執行一個ModelState.AddModelError(),而在屬性的OnActionExecuting()方法,該方法將節省我使控制器執行這個邏輯。

我已經嘗試添加一個ModelState屬性屬性,但這個數據似乎沒有可用傳入屬性。

有沒有一種方法可以從屬性中訪問ModelState?

回答

8

假設你的控制器類從System.Web.Mvc.Controller派生(可能是這種情況),你可以試試這個:

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

呸!我之前嘗試過的時候並沒有想到要投它。謝謝。 – 2009-07-02 15:20:42

相關問題