2017-08-14 22 views
0

我試圖驗證基於在列表自定義驗證的對象的名單MVC

public class CustomerModel 
    {  
      public List<CustomerBrand> Brands { get; set; } 

    } 
    } 
    public class CustomerBrand 
    {    
     public int Priority { get; set; } 
     public bool Checked { get; set; } 
    } 

按照下面如果一個複選框被選中另一場申請,然後在文本框中輸入的值必須大於比零。任何人都可以幫忙帶,它可將驗證模型的解決方案,並從控制器

enter image description here

我已工作中使用此方法,但希望能夠指明違規行。

public class CustomerModel : IValidatableObject 
    { 
     public string Name { get; set; } 

     public List<CustomerBrand> Brands { get; set; } 

     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
     { 
      foreach(var brand in Brands) 
      { 
       if(brand.Checked) 
       { 
        if(brand.Priority < 1) 
        { 
         yield return new ValidationResult("Priority must be greater than 1"); 
        } 
       } 
      } 
     } 
    } 
+1

[屬性依賴於另一個字段]的可能重複(https://stackoverflow.com/questions/3713281/attribute-dependent-on-another-field) – Marco

回答

0

怎麼是這樣的:

int x = 1; 
foreach(var brand in Brands) 
{ 
    if(brand.Checked) 
    { 
     if(brand.Priority < 1) 
     { 
      yield return new ValidationResult("Item " + x.ToString() + " - Priority must be greater than 1"); 
     } 
    } 
    x++; 
} 

如果你有辦法比列表中的位置以外的東西來指代項目,你可以使用,而不是X