Asp.net mvc 如何在asp.net mvc 3中使用jquery和dataannotation验证输入文件

Asp.net mvc 如何在asp.net mvc 3中使用jquery和dataannotation验证输入文件,asp.net-mvc,validation,asp.net-mvc-3,jquery-validate,data-annotations,Asp.net Mvc,Validation,Asp.net Mvc 3,Jquery Validate,Data Annotations,我确信我在这里遗漏了一些东西,我发现了一个验证文件的问题,这是示例代码 public class UpdateSomethingViewModel { [DisplayName("evidence")] [Required(ErrorMessage="You must provide evidence")] [RegularExpression(@"^abc123.jpg$", ErrorMessage="Stuff and nonsense")] public

我确信我在这里遗漏了一些东西,我发现了一个验证文件的问题,这是示例代码

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.defence)

有什么想法吗

更新
我在html属性集合中找到了一个传递属性类型的简单解决方案

 @Html.TextBoxFor(model => model.Evidence, new { type = "file" })
 @Html.ValidationMessageFor(model => model.Evidence)
@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
类型。当您为此控制器操作编写单元测试时,这将使您的生活更加轻松。

我在html属性集合中找到了一个传递属性
类型
的简单解决方案

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

我发现,尽管这一切都在客户端工作,但由于Regex验证器的原因,ModelState.IsValid返回false。