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

标签 c# asp.net-mvc data-annotations

我正在尝试使用数据注释来验证表单。这对于字符串类型和整数来说似乎很棒,但是对于文件上传,我无法从类里面进行验证。它只会被发送一个字符串“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 中)并且它很有效。

希望对您有所帮助。

干杯, 特里

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

相关文章:

c# - 如何发布数据并重定向到外部页面?

c# - 为什么PauseToken会中断任务?

asp.net-mvc - 为什么选择Moles作为我的模拟框架?

asp.net-mvc - 使用 "tel:"标签时,出现 "A potentially dangerous Request.Path value was detected from the client (:). "错误

c# - asp.NET MVC 2 DataAnnotations UpdateModel<T> 验证

jquery - MVC 3 客户端对带有数据注释的集合进行验证 - 不起作用

c# - 将两个 lambda 与表达式相乘

c# - 我如何跟踪对数据库表的任何更改

c# - 如何通过带有 header 的 HttpClient 将复杂对象发布到 Controller 的 Post 方法?

asp.net-mvc - 属性级验证错误阻碍了类级验证的验证