2012-06-20 36 views
1

我有用於驗證集合的自定義驗證屬性。我需要適應這與IEnumerable工作。我試着讓這個屬性成爲一個通用屬性,但是你不能擁有一個通用屬性。ValidationAttribute for IEnumerable Property

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 
public class CollectionHasElements : System.ComponentModel.DataAnnotations.ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     if (value != null && value is IList) 
     { 
      return ((IList)value).Count > 0; 
     } 
     return false; 
    } 
} 

我無法將其轉換爲IEnumerable,因此我可以檢查它的count()或any()。

任何想法?

+0

您是否嘗試過'ICollection'類型? – SPFiredrake

+0

更改類型不是一個選項。這些對象正在從EF填充。 – Darthg8r

+0

你可以對'IEnumerable'進行轉換,例如:'IEnumerable en = value as IEnumerable; if(en!= null){...}'? – Tejs

回答

5

試試這個

var collection = value as ICollection; 
if (collection != null) { 
    return collection.Count > 0; 
} 

var enumerable = value as IEnumerable; 
if (enumerable != null) { 
    return enumerable.GetEnumerator().MoveNext(); 
} 

return false; 

注:測試的ICollection.Count比得到一個枚舉,並開始枚舉枚舉更有效率。因此,我儘可能使用Count屬性。但是,第二個測試將單獨工作,因爲收集始終實施IEnumerable

繼承層次結構如下所示:IEnumerable > ICollection > IListIList器具ICollectionICollection器具IEnumerable。因此IEnumerable將適用於任何設計良好的收集或枚舉類型,但不適用於IList。例如Dictionary<K,V>不實施IList,但是ICollection,因此也實施IEnumeration


.NET命名約定表明屬性類名稱應始終以「屬性」結尾。因此你的班級應該被命名爲CollectionHasElementsAttribute。應用該屬性時,可以刪除「屬性」部分。

[CollectionHasElements] 
public List<string> Names { get; set; } 
0

所需的驗證屬性的列表和複選框列表

[AttributeUsage(AttributeTargets.Property)] 
public sealed class CustomListRequiredAttribute : RequiredAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     var list = value as IEnumerable; 
     return list != null && list.GetEnumerator().MoveNext(); 
    } 
} 

如果你有複選框列表

[AttributeUsage(AttributeTargets.Property)] 
public sealed class CustomCheckBoxListRequiredAttribute : RequiredAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     bool result = false; 

     var list = value as IEnumerable<CheckBoxViewModel>; 
     if (list != null && list.GetEnumerator().MoveNext()) 
     { 
      foreach (var item in list) 
      { 
       if (item.Checked) 
       { 
        result = true; 
        break; 
       } 
      } 
     } 

     return result; 
    } 
} 

這裏是我的視圖模型

public class CheckBoxViewModel 
{   
    public string Name { get; set; } 
    public bool Checked { get; set; } 
} 

使用

[CustomListRequiredAttribute(ErrorMessage = "Required.")] 
public IEnumerable<YourClass> YourClassList { get; set; } 

[CustomCheckBoxListRequiredAttribute(ErrorMessage = "Required.")] 
public IEnumerable<CheckBoxViewModel> CheckBoxRequiredList { get; set; } 
相關問題