有没有一种方法可以验证MVC 2中传入的HttpPostedFilebase文件?

问题描述

| 除了一些简单的标量数据之外,我还需要保存几个文件。我是否可以验证文件是否已与其余表单数据一起发送?我正在尝试使用
[required]
属性,但似乎无法正常工作。     

解决方法

以下对我有用。 模型:
public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}
控制器:
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\");
    }
}
视图:
<% 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\" />
<% } %>