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

本文关键字:验证 文件 HttpPostedFilebase MVC 一种 方法 有没有 | 更新日期: 2023-09-27 17:57:35

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

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

以下内容对我有效。

型号:

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" />
<% } %>