2010-09-04 91 views
0

我跟隨scottgu的博客here並試圖做數據驗證。成功了。但是我看到的是,如果我的字段是必填字段,那麼只要我從我的文本框中放鬆焦點,就會收到錯誤消息。我希望只有當我點擊提交時才能進行驗證。通過DataAnnotations進行ASP.Net MVC驗證

回答

0

該文章是關於使用客戶端驗證,因此您可以在客戶端驗證您的表單。由於這個原因,當你失去焦點時,表單會被jquery驗證!

一種方法是使用服務器端驗證..我這種情況下,你將有一個頁面刷新。

更新:

下面是示例代碼。
型號:

public class GuestForm 
    { 
     [Required(ErrorMessage="Please enter your name")] 
     public string Name { get; set; } 

     [Required(ErrorMessage="Please enter your phone number")] 
     public string Phone { get; set; } 

     [Required(ErrorMessage="Please enter your email address")] 
     public string Email { get; set; } 

     [Required(ErrorMessage = "Please enter your choice")] 
     public bool? YesNo { get; set; } 
    } 

形式:

<div> 
<% using(Html.BeginForm()) { %> 
    <%= Html.ValidationSummary() %> 
    Name: <%= Html.TextBoxFor(x => x.Name) %><br/> 
    Email: <%= Html.TextBoxFor(x => x.Email) %><br/> 
    Phone: <%= Html.TextBoxFor(x => x.Phone) %><br/> 
    Will you attend? 
    <%= Html.DropDownListFor(x => x.YesNo, new[] { 
     new SelectListItem { Text = "Yes",Value = bool.TrueString }, 
     new SelectListItem { Text = "No",Value = bool.FalseString } 
     }, "Choose...") %><br/> 
    <input type="submit" value="Register!" /> 
<% } %> 
</div> 

控制器:

 [HttpGet] 
     public ViewResult RegisterForm() 
     { 
      return View(); 
     } 

     [HttpPost] 
     public ViewResult RegisterForm(GuestForm form) 
     { 
      if (ModelState.IsValid) 
       return View("Thanks", form); 
      else 
       return View(); 
     } 

該代碼會看到你的形式在服務器端驗證用戶時,點擊提交。 它將以列表的形式在窗體頂部顯示錯誤消息。

我希望這可以幫助你。

+0

我明白了。但是,在簡單的網頁場景中,除非您單擊提交按鈕,否則驗證不會發生。我希望我的用戶看到錯誤合併列表,然後採取相應措施。在每次失去焦點後發現錯誤可能會減少用戶的交互。 – Ashish 2010-09-04 10:51:54

+0

@Ted,這是可能的..我會提交與示例代碼的另一個答案作爲評論粘貼代碼可以使其不可讀。 – 2010-09-04 11:07:27

+0

@特德,檢查更新的答案 – 2010-09-04 11:22:42

相關問題