1

如何有條件地禁用某些字段的客戶端驗證?爲ASP.NET MVC中的某些字段禁用客戶端驗證

這裏是什麼,我需要做的例子:

  • 用戶寫的名字和地址,並提交。
  • 兩者都經過服務器端和客戶端的驗證。如果驗證通過,電子郵件將發送到給定地址,並且(名稱,地址)對被存儲。
  • 作爲響應顯示同一頁面(我不想重定向!)這一次與確認。用戶可以重新鍵入他們的名字並提交。在這種情況下,電子郵件將被重新發送到與給定名稱相對應的地址。

它不起作用,因爲:當用戶單擊第二個(確認屏幕)上的重新發送按鈕時,客戶端驗證將不會通過。它會說即使沒有字段,也需要電子郵件。在確認頁面發送給用戶之前,如何禁用javascript驗證電子郵件?

例ASP.NET頁面MVC

<%if (Model.Confirm == false){ %> 
    <% using (Html.BeginForm()) { %> 
     Your email: <%: Html.EditorFor(m => m.Email) %> 
     Your name: <%: Html.EditorFor(m => m.Name) %> 
     <input type="submit" value="Send Email" /> 
    <% } %> 
<%} else{ %> 
    The e-mail was send! You can write your name and click button to resend it. 
    <% using (Html.BeginForm()) { %> 
     Your name: <%: Html.EditorFor(m => m.Name) %> 
     <input type="submit" value="Resend me email again" /> 
    <% } %> 
<% } %> 

在該模型中都EmailName需要字段來執行客戶端驗證。

例控制器動作

public ActionResult Index(){ 
    return new MyModel {Confirm = false;} 
} 

[HttpPost] 
public ActionResult Index(MyModel model){ 
    if(DataHelper.isKnown(model.Name)){ 
     //send e-mail to the address corresponding to name in database 
    } 
    if(!ModelState.IsValid) { 
     return View(model); 
    } 
    //Send e-mail to address in email 
    //store pair name->email to database 
    model.Confirm = true; 
    return View(model); 
} 

回答

1

爲什麼不使用2種不同的視圖?你不必重定向。我認爲你在這裏違反了SRP。這種觀點不止一個目的。

public ActionResult SubmitEmail(Model model) 
{ 
    if(!emailWasSent) 
     return View("FirstView"); 
    else 
     return View("ConfirmationView"); 
} 

這樣第一個視圖可以有客戶端驗證,第二個視圖不能選擇它並按照它的意願去做。

+0

是的,我是...很棒的筆記,謝謝! – drasto 2011-03-22 09:02:40

2

正是由於這個簡單的解決方案,我會隱藏第二個確認電子郵件字段並保持其價值。

<%} else{ %> 
    The e-mail was send! You can write your name and click button to resend it. 
    <% using (Html.BeginForm()) { %> 
     <%: Html.HiddenFor(m => m.Email) %> 
     Your name: <%: Html.EditorFor(m => m.Name) %> 
     <input type="submit" value="Resend me email again" /> 
    <% } %> 
<% } %> 
+0

是的,這是我想到的一種解決方案。但我不想這樣做。我的例子只是一個例子,我不喜歡這個想法,如果發送可能大量的用戶輸入和回來。還有像密碼這樣的敏感數據。我知道他們至少發送一次,但我不想只發送一次以上。 – drasto 2011-03-21 09:17:09

1

我想,在這裏它不是全部或全部問題。因此,您需要禁用該視圖的客戶端驗證並手動檢查要驗證的控件。 (離開我的頭頂)。

編輯:如果我想做手動客戶端驗證,我會使用jQuery,因爲它在這樣的任務是如此直截了當。

+0

那麼我該如何禁用代碼**中的所有驗證**?沒有什麼像'Html.DisableClientSideValidation()'... – drasto 2011-03-21 09:13:48

+3

像這樣'Html.EnableClientSideValidation(false)' – 2011-03-21 09:18:17

+2

它是Html。EnableClientValidation(false)(至少現在在MVC 4中) – 2013-01-03 12:08:39