有没有一种方法来验证MVC 2的传入HttpPostedFilebase文件? [英] Is there a way to validate incoming HttpPostedFilebase files in MVC 2?

查看:117
本文介绍了有没有一种方法来验证MVC 2的传入HttpPostedFilebase文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一对夫妇,我需要除了保存一些简单的标量数据文件。有没有办法对我来说,以验证文件已与表单数据的其余部分一起发送?我试图使用 [必需] 属性,但它似乎并不奏效。

I have a couple of files I need to save in addition to some simple scalar data. Is there a way for me to validate that the files have been sent along with the rest of the form data? I'm trying to use the [Required] attribute, but it doesn't seem to be working.

推荐答案

下面为我工作。

型号:

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

这篇关于有没有一种方法来验证MVC 2的传入HttpPostedFilebase文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆