【问题标题】:how to validate input file with jquery and dataannotation in asp.net mvc 3如何在asp.net mvc 3中使用jquery和dataannotation验证输入文件
【发布时间】:2011-09-11 06:04:50
【问题描述】:

我确定我在这里遗漏了一些东西,我找到了this 验证文件的问题,这里是示例代码

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)

【问题讨论】:

    标签: asp.net-mvc validation asp.net-mvc-3 jquery-validate data-annotations


    【解决方案1】:

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

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

    【讨论】:

    • 我发现,尽管这一切都在客户端工作,但由于正则表达式验证器,ModelState.IsValid 返回 false。
    【解决方案2】:

    恐怕您无法使用数据注释来做到这一点。您可以在应该处理请求的控制器操作中执行此操作:

    型号:

    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 类型。当您为此控制器操作编写单元测试时,它会让您的生活更轻松。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      相关资源
      最近更新 更多