我正在尝试使用数据注释来验证表单。对于字符串类型和整数似乎很棒,但是对于文件上传,我无法从类中进行验证。它只会被发送一个字符串“ HttpPostedFileWrapper”。有人有提示吗?

谢谢

最佳答案

您可以按照常规用法使用数据注释。

例如,如下视图模型:

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中),但它确实有效。

希望能有所帮助。

干杯,
特里

关于c# - asp.net MVC 2验证带有数据注释的文件上传,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2408008/

10-13 05:03