MVC。 HttpPostedFileBase总是空 [英] MVC. HttpPostedFileBase is always null

查看:855
本文介绍了MVC。 HttpPostedFileBase总是空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助。我试图通过上传&LT文件;输入类型=文件> 。这是我的观点:

I need some help. I'm trying to upload files using <input type="file">. Here is my View:

@using (Html.BeginForm("BookAdd", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="files[0]" id="files[0]" />
    <input type="file" name="files[1]" id="files[1]" />
    <input type="submit" value="Upload Book" />
}

这是应当处理上传文件的操作。

And here is an Action which should process uploaded file.

[HttpPost]
public ActionResult BookAdd(IEnumerable<HttpPostedFileBase> files)
{
    // some actions
    return View();
}

的问题是,文件总是包含两个元件,其是空的。
可以做些什么来解决这个问题?

The problem is that "files" always contains two elements which are null. What can be done to fix it?

这时候的一些消息。好像我发现了这个问题,但我仍然不知道如何解决它。看来,尽管我使用的multipart / form-data的在这里:

It's time for some news. It seems like I found the problem, but I still don't know how to fix it. It appears that despite the fact I'm using "multipart/form-data" here:

@using (Html.BeginForm("BookAdd", "Admin", FormMethod.Post, new { enctype="multipart/form-data" }))
{
    <input type="file" name="File" id="file1" />
    <input type="file" name="File" id="file2" />
    <input type="submit" value="Upload Book" />
}

Request.ContentType 仍然是应用程序/ x-WWW论坛-urlen codeD的控制器。

Request.ContentType remains "application/x-www-forum-urlencoded" in controller..

推荐答案

在你的输入字段的名称刚刚摆脱的方括号:

Just get rid of the square brackets in the names of your input fields:

@using (Html.BeginForm("BookAdd", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="files" id="file1" />
    <input type="file" name="files" id="file2" />
    <input type="submit" value="Upload Book" />
}


更新:

看着你寄给我的样本项目后的问题是,你有2个嵌套形式。这不是在HTML中不允许的。你在你的 _Layout.cshtml 一种形式,并在你的 BookAdd.cshtml 视图另一种形式。这就是为什么尽管你内心的形式你得到错误的 ENCTYPE =的multipart / form-data的属性 Request.ContentType 。所以,你将不得不UNNEST这些形式,如果你想这个工作。另外,在例子中,你送我你的 BookAdd 控制器行为不具有正确的签名以文件的列表,但我想这是由于一些测试,你在干什么。

After looking at the sample project you sent me the problem is that you have 2 nested forms. This is not allowed in HTML. You have one form in your _Layout.cshtml and another form in your BookAdd.cshtml view. That's the reason why despite the enctype="multipart/form-data" attribute on your inner form you were getting the wrong Request.ContentType. So you will have to unnest those forms if you want this to work. Also in the example you sent me your BookAdd controller action doesn't have the correct signature taking a list of files, but I guess that's due to some tests you were doing.

这篇关于MVC。 HttpPostedFileBase总是空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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