代码之家  ›  专栏  ›  技术社区  ›  Francis Gilbert

ASP.NET MVC 2使用数据批注验证文件上载

  •  1
  • Francis Gilbert  · 技术社区  · 16 年前

    我正在尝试使用数据批注验证表单。它对于字符串类型和整数似乎很好,但是对于文件上传,我无法从类中验证。它只会被发送一个字符串“httppostedfilewrapper”。有人有什么建议吗?

    谢谢

    1 回复  |  直到 16 年前
        1
  •  4
  •   Terry_Brown    16 年前

    您可以根据一般用法使用数据注释。

    例如,视图模型,例如:

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

    然后在你的控制器里像往常一样:

    [HttpPost]
    public ActionResult UpdateSomething(UpdateHSomethingViewModel model)
    {
        if (ModelState.IsValid)
        {
            // do stuff - plenty of stuff
            // weee, we're off to see the wizard.
    
            return RedirectToAction("UpdateSomethingSuccess", model);
        }
    
        return View(model);
    }
    

    我刚刚进行了测试(尽管是在mvc2/.net 4中),结果很不错。

    希望能有所帮助。

    干杯, 特里