【问题标题】:File uploading causes invalid model state in asp.net mvc文件上传导致asp.net mvc中的模型状态无效
【发布时间】:2015-05-06 03:28:42
【问题描述】:

一直在尝试实现包含多个文件的文件上传器,但我不断收到无效的ModelState。这是我的代码(只是必需品)

视图模型:

public IEnumerable<HttpPostedFileBase> files { get; set; }

view.cshtml:

@model ITManagement.ViewModels.AssetViewModel

@using (Html.BeginForm(new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
    <h4>Asset</h4>
    <hr />
.
. The rest of the form is located here
. 
.
    <div class="form-group">
        @Html.LabelFor(viewModel => viewModel.objectModel.documentInfo.documents.fileContent, htmlAttributes: new {@class = "control-label col-md-2" } )
        <div class="col-md-2">
            <input class="single-line" id=@Html.IdFor(viewModel => viewModel.files)
                   name=@Html.NameFor(viewModel => viewModel.files)
                   type="file" multiple="multiple" />
        </div>
    </div>

控制器:

    [Route("create", Name = AssetsControllerRoute.Create)]
    public ActionResult create()
    {
        AssetViewModel evm = new AssetViewModel();
        return View(evm);
    }

    // POST: Assets/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    [Route("create")]
    public ActionResult create(AssetViewModel asset)
    {
        if (ModelState.IsValid)
        {
            erepo.add(asset.objectModel);
            return RedirectToAction("Index");
        }

        return View(asset);
    }

我已经遇到过this question,然后是this error and answer,但我仍然缺少一些东西。当我上传文件并提交表单时,files 变量为空。我确实在搜索中看到使用 Request.Files,但是尝试绑定到 IEnumerable&lt;HttpPostedFileBase&gt; 和使用 Request.Files 有什么区别?

这是无效模型状态的原因:

“从类型'System.String'到类型'System.Web.HttpPostedFileBase'的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。”

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    我错的一段代码是这样的

    @using (Html.BeginForm(new { enctype = "multipart/form-data" }))
    

    这应该是

    @using (Html.BeginForm("create", "assets", FormMethod.Post, new { enctype = "multipart/form-data" }))
    

    “create”代表控制器动作,“assets”代表控制器名称。我给了它这3个参数,一切都很好。

    【讨论】:

    • 澄清一下,问题是缺少enctype,这是发布文件所必需的。顶部代码 sn-p 尝试使用根本不存在的重载。接受一个对象的重载设置路由值,而不是 HMTL 属性。
    • @Sinjai 我会反驳你所说的 enctype 是在顶部代码 sn-p 中指定的。我只是为需要发生的事情使用了错误的重载。
    • 当然,“enctype”这个词在第一个 sn-p 中。但是您实际上并没有设置它,因此出现了错误。我只是想为任何未来的读者添加一个注释。否则,问题的核心可能是模棱两可的——即您是否需要指定操作/控制器?表单方法?我是因为忘记了 HTML 属性中的 enctype 而被带到这里的。
    • @Sinjai 说问题是“缺少某些东西”通常意味着(至少对我而言)它完全丢失了。我明白你的观点,但它是有效的。我最终使用了不正确的重载用法,因为我不了解 MS 的文档或当时的任何原因。
    • 当然,我可能应该说“在呈现的 HTML 中缺少 enctype”。
    猜你喜欢
    • 2016-04-04
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    相关资源
    最近更新 更多