有没有办法验证MVC 2中传入的HttpPostedFilebase文件?

Maj*_*ons 1 c# validation file-upload asp.net-mvc-2

除了一些简单的标量数据外,我还需要保存几个文件.有没有办法让我验证文件是否已与其余表单数据一起发送?我正在尝试使用该[Required]属性,但它似乎不起作用.

Dar*_*rov 7

以下对我有用.

模型:

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var fileName = Path.GetFileName(model.File.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
        model.File.SaveAs(path);
        return RedirectToAction("Index");
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
    <input type="file" name="file" />    
    <%= Html.ValidationMessageFor(x => x.File) %>
    <input type="submit" value="OK" />
<% } %>
Run Code Online (Sandbox Code Playgroud)