Skip to main content
 首页 » 编程设计

c#之asp.net MVC 2 使用数据注释验证文件上传

2024年02月24日21wuhuacong

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

谢谢

请您参考如下方法:

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

例如,一个 View 模型如:

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

然后在你的 Controller 中像往常一样:

[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 中)并且它很有效。

希望对您有所帮助。

干杯, 特里