2012-04-05 120 views
1

我不確定標題是否清晰。讓我更好地解釋它:驗證註釋模型列表

我有兩個型號:

1個GuestResponse.cs:

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

     [Required(ErrorMessage = "Please enter your email address")] 
     [RegularExpression(".+\\@.+\\..+", ErrorMessage="Please enter a valid email address")] 
     public string Email { get; set; } 

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

     [Required(ErrorMessage = "Please especify wheter you will attend")] 
     public bool? WillAttend { get; set; } 
    } 

2- CompanyGuestResponse.cs:

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

     [Required(ErrorMessage = "Please enter your company email address")] 
     [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please enter a valid email address")] 
     public string Email { get; set; } 

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

     public IList<GuestResponse> GuestResponses { get; set;} 
    } 

我也有一個強烈CompanyGuestResponse模型的視圖,其中有一個表格,可讓用戶爲屬性GuestResponses提供輸入。

我想只能在表格的填充行被正確驗證(即,不要試圖驗證沒有填充的行)並且至少有一行被正確填充的情況下才能提交表單。

我試圖通過與沒有成功ViewModel validation for a List描述創建自定義註釋來做到這一點(MVC根本無視列表註釋和驗證在GuestResponse類註釋):

[EnsureOneElementAttribute(ErrorMessage = "At least a person is required")] 
public IList<GuestResponse> GuestResponses { get; set;} 

結果:

http://postimage.org/image/b2jn7ta69/

回答

0

什麼,我知道你是想驗證每個域的模型本身,而不是,所以你可以做什麼去除性能的[Required]屬性, d在動作驗證,如果任何字段都被填充了,如果這樣再繼續否則,添加一個錯誤,並且不與任何領域

等什麼我告訴你在這種情況下降附註關聯,並做了人工檢查