2015-04-23 77 views
2

我在表單上有兩個具有不同名稱的提交按鈕。在控制器 我有一個單一的HttpPost操作方法,當我點擊兩個提交按鈕中的任何一個時,我會調用它。下面是操作方法的內部:如何防止Fluent驗證在某些情況下驗證模型

public ActionResult Save(Document model){ 
    if(Request["btnSave"]!=null){ 
     if (ModelState.IsValid){ 
     //go ahead and save the model to db 
     } 
    }else{//I don't need the model to be validated here 
     //save the view values as template in cache 
    } 
} 

所以,當名稱爲「btnSave」點擊我需要的模式按鈕將它保存到數據庫,但如果點擊另一個按鈕,我不前必須被確認t需要任何驗證,因爲我只是將表單值保存在緩存中,以便稍後將其返回。很明顯,在這種情況下我不需要驗證任何東西。我使用Fluent驗證。我的問題是無論按下哪個按鈕,我都會收到警告。我可以控制FV何時驗證模型嗎?

+0

你需要防止客戶端驗證提交表單或視圖時行動執行後返回? –

+0

在執行操作後返回? –

+0

我不知道我理解你的目標:你想在第二個按鈕點擊的情況下防止任何服務器端驗證規則執行? –

回答

1

您可以添加屬性btnSave到模型:

public class Document 
{ 
    public string btnSave {get; set;} // same name that button to correctly bind 
} 

而在你驗證使用條件驗證:

public class DocumentValidator : AbstractValidator<Document> 
{ 
    public DocumentValidator() 
    { 
     When(model => model.btnSave != null,() => 
     { 
      RuleFor(...); // move all your document rules here 
     }); 

     // no rules will be executed, if another submit clicked 
    } 
} 
+1

Haaaa,這是一個非常好的主意。事實上,我接近這一點,我只是不知道我可以寫一個「獨立的」當它涵蓋所有的驗證邏輯。 –

相關問題