2017-04-15 106 views
1

基本上我想弄清楚的是如何要求在視圖中填寫兩個字段中的至少一個。要求一個或另一個字段

在我的視圖中,我有兩個名爲ISBN和ISBN13的文本字段。只要其中一個被填充,用戶填充哪一個並不重要。

我不確定這裏要做什麼期望看看寫入自定義驗證程序,所以我想我會先問。我會包含一些代碼,但因爲它只是兩個簡單的字段,我認爲這個解釋會更好。

+2

你可以對發佈在這個問題上的答案做一個小的改變,以獲得你想要的東西http://stackoverflow.com/questions/11959431/how-to-create-a-custom-validation-attribute?rq=1 – Shyju

+0

自定義代碼在這裏絕對適合。事實上,你甚至不需要自定義驗證器;這是核心領域的業務邏輯,而不僅僅是UI關注。在無效狀態下創建實體應該是不可能的(例如,您可以在構造中添加投擲代碼以驗證此功能)。在UI中單獨的javascript驗證有助於爲用戶提供即時反饋 –

回答

1

我想象一下,在保存到數據庫的更改之前,在創建部分添加類似這樣的內容到您的控制器。

int countISBN = Product.ISBN.Count() + Product.ISBN13.Count(); 
if (countISBN <= 9) 
{ 
    // Add in an error message. 
    return View(); 
} 

這將做的是統計兩個字段中的字符,將它們相加。如果他們的總和低於10,它會拋出一個錯誤。

1

使用MVC Foolproof NuGet包,然後你可以使用RequiredIf屬性象下面這樣:

[RequiredIf("ISBN==\"\"")] // backslash is used for escaping the quotes 
public string ISBN13 { get; set; } 

[RequiredIf("ISBN13==\"\"")] 
public string ISBN { get; set; } 
2

你可以在你的控制器動作做了人工確認。 AddModelError方法將幫助您使用驗證堆棧。

[HttpPost] 
public ActionResult Edit(EditModel model) 
{ 
    if (string.IsNullOrEmpty(model.ISBN) && string.IsNullOrEmpty(model.ISBN13)) 
    { 
     var validationMessage = "Please provide ISBN or ISBN13."; 
     this.ModelState.AddModelError("ISBN", validationMessage); 
     this.ModelState.AddModelError("ISBN13", validationMessage); 
    } 

    if (!string.IsNullOrEmpty(model.ISBN) && !string.IsNullOrEmpty(model.ISBN13)) 
    { 
     var validationMessage = "Please provide either the ISBN or the ISBN13."; 
     this.ModelState.AddModelError("ISBN", validationMessage); 
     this.ModelState.AddModelError("ISBN13", validationMessage); 
    } 

    if (this.ModelState.IsValid) 
    { 
     // do something with the model 
    } 

    return this.View(model); 
} 

有些人可能會說,對查詢進行驗證不是控制器的責任。我認爲控制者的責任是將網絡請求調整爲域請求。因此,控制器可以有驗證邏輯。如果您沒有域/業務層,則這種考慮是沒有意義的。

相關問題