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

标签 c# asp.net-mvc-2 file-upload validation

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

最佳答案

以下对我有用。

型号:

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}

Controller :

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

关于c# - 有没有办法验证 MVC 2 中传入的 HttpPostedFilebase 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6126472/

相关文章:

c# - 使用 SharpDX 从 WAV 编码为 AAC 并从 AAC 解码为 WAV

C# 数字基类

c# - 是否可以在 Dynamics CRM (2013/2016) 中以编程方式禁用审计?

asp.net-mvc - ASP.NET MVC2 项目使用哪个数据网格?

java - 使用java后端Ajax文件上传?

c# - 美国运通的 ISO8583

asp.net-mvc-2 - MVC 2项目中强类型HtmlHelper扩展方法源代码在哪里?

c# - 如何修复不允许子操作执行重定向操作,其他答案未修复

php - Amazon EC2 Ubuntu 实例最大文件上传大小

java - spring mvc中不存在必需的MultipartFile参数 'file'