0

我在我的網站上得到了jquery(原始,驗證&不顯眼)。我已經擴展了一個在服務器端工作的驗證屬性,但是我不能在我的生活中讓它在客戶端工作。我錯過了什麼?在jquery不顯眼的客戶端驗證HttpPostedFileBase

我的模型看起來是這樣的:

[Display(Name = "UploadFile"), DataType(DataType.Upload)] 
[ValidateFile] 
public IEnumerable<HttpPostedFileBase> MyImage { get; set; } 

我加入這個屬性擴展到我的模型:

public class ValidateFileAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     int MaxContentLength = 1024 * 1024 * 10; //10 MB 
     string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" }; 
     var files = value as IEnumerable<HttpPostedFileBase>; 

     foreach (var file in files) 
     { 
      if (file == null) 
      { 
       return false; 
      } 
      else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.')))) 
      { 
       ErrorMessage = Resources.ResourcesAdvert.AdvertUploadFileExtensionErrorShorter + string.Join(", ", AllowedFileExtensions); 
       return false; 
      } 
      else if (file.ContentLength > MaxContentLength) 
      { 
       ErrorMessage = Resources.ResourcesAdvert.AdvertUploadFileTooBig + (MaxContentLength/1024).ToString() + "MB"; 
       return false; 
      } 
      else 
      { 
       return true; 
      } 
     } 
     return false; 
    } 
} 

我有這樣一個觀點:

@Html.LabelFor(x => x.MyImage) 

<input type="file" name="MyImage[0]" id="MyImage1" /> 
<input type="file" name="MyImage[1]" id="MyImage2" /> 
<input type="file" name="MyImage[2]" id="MyImage3" /> 

@Html.ValidationMessageFor(x => x.MyImage) 

我的控制器工作正常,如果它們有效,它就可以上傳圖像。任何想法我可以如何繼續?

編輯:我也試過使用this,但這並不適用於我的客戶端,我無法設置自定義錯誤消息。

+0

最好爲FileSize和FileType創建單獨的驗證屬性。請參考[這個答案](http://stackoverflow.com/questions/33414158/checking-image-mime-size-etc-in-mvc/33426397#33426397)爲'FileTypeAttribute' –

+0

的例子可能會很好理念。我會開始研究這個。 – guitarzero

+0

另請參閱[本文](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2)以獲取良好指南創建支持客戶端驗證的驗證屬性 –

回答

0

由於沒有答案,我會分享一些信息,以防其他人遇到同樣的問題。

我最終通過鏈接@Stephen Muecke提供的(here)解決了這個問題。我的問題是沒有正確配置javascript,因爲我不知道在哪裏放置每個變量。