2014-01-08 35 views
0

我爲整個圖像編寫了驗證屬性。 我有兩個屬性(HttpPostedFileBase,ICollection <HttpPostedFileBase>)。我可以檢查第一個但不是第二個。如何瀏覽ICollection <HttpPostedFileBase>項目並檢查其類型

[MyFileType(" jpg , jpeg , png ")] 
public HttpPostedFileBase file128 { get; set; } 
public ICollection<HttpPostedFileBase> file900 { get; set; } 

public class MyFileTypeAttribute : ValidationAttribute 
{ 
    private readonly List <string> myTypes; 
    public MyFileTypeAttribute(string _types) 
    { 
     MyTypes =_types. Split (' , ').tolist(); 
    } 
    public override boo Isvalid (object _value) 
    { 
     if (_value == null) 
     { 
      return true ; 
     } 

     var fileExt = System.IO.Path.GetExtention ((_value as HttpPostedFileBase).FileName).Substring (1); 
     return MyTypes. Contains (fileExt , StringComparer.OrdinalIgnoreCase); 
    } 

    public override string FormatErrorMessage (string _name) 
    { 
     return String.Format (" invalid file type .only following types : {0} are supported . " , String.join ("," , MyTypes)); 
    } 
} 

我可以檢查HttpPostedFileBase,但我怎麼能瀏覽的ICollection <HttpPostedFileBase>項目,並檢查它們的類型?

回答

0

在代碼的情況下:

[MyFileType(" jpg , jpeg , png ")] 
public ICollection<HttpPostedFileBase> file900 { get ; set; } 

屬性關於集合本身,但是你可以,如果收藏價值被指定屬性中IsValid檢查。類似(未測試)代碼:

public override bool Isvalid (object _value) 
{ 
    var col = _value as ICollection<HttpPostedFileBase>; 
    if (col != null) 
    { 
     // check each element; 
     return col.All(x => IsValid(x)); 
    } 
    else 
    { 
     var fileExt = System.IO.Path.GetExtention((_value as HttpPostedFileBase).FileName).Substring(1); 
     return MyTypes.Contains (fileExt, StringComparer.OrdinalIgnoreCase); 
    } 
} 
相關問題