Asp.net-Mvc

如何在asp.net mvc 3中使用jquery和dataannotation驗證輸入文件

  • June 10, 2011

我確定我在這裡遺漏了一些東西,我發現這個問題是為了驗證文件,這裡是範常式式碼

public class UpdateSomethingViewModel 
{
   [DisplayName("evidence")]
   [Required(ErrorMessage="You must provide evidence")]
   [RegularExpression(@"^abc123.jpg$", ErrorMessage="Stuff and nonsense")]
   public HttpPostedFileBase Evidence { get; set; }
}

但我沒有看到任何@Html.FileFor(model => model.Evidence)

有任何想法嗎?

更新

我在 html 屬性集合中找到了一個簡單的傳遞屬性類型的解決方案。

@Html.TextBoxFor(model => model.Evidence, new { type = "file" })
@Html.ValidationMessageFor(model => model.Evidence)

type我在 html 屬性集合中找到了一個簡單的傳遞屬性的解決方案。

@Html.TextBoxFor(model => model.Evidence, new { type = "file" })
@Html.ValidationMessageFor(model => model.Evidence)

恐怕你不能使用數據註釋來做到這一點。您可以在應該處理請求的控制器操作中執行此操作:

模型:

public class UpdateSomethingViewModel 
{
   [DisplayName("evidence")]
   [Required(ErrorMessage = "You must provide evidence")]
   public HttpPostedFileBase Evidence { get; set; }
}

行動:

[HttpPost]
public ActionResult Foo(UpdateSomethingViewModel model)
{
   if (model.Evidence != null && model.Evidence.ContentLength > 0)
   {
       // the user uploaded a file => validate the name stored
       // in model.Evidence.FileName using your regex and if invalid return a
       // model state error
       if (!Regex.IsMatch(model.Evidence.FileName, @"^abc123.jpg$"))
       {
           ModelState.AddModelError("Evidence", "Stuff and nonsense");
       }
   }
   ...
}

另請注意,最好使用HttpPostedFileBase而不是模型中的具體HttpPostedFileWrapper類型。當您為此控制器操作編寫單元測試時,它將使您的生活更輕鬆。

引用自:https://stackoverflow.com/questions/6285624