asp.net-mvc-3 - MVC。 HttpPostedFileBase始终为null

标签 asp.net-mvc-3

我需要协助。我正在尝试使用<input type="file">上传文件。这是我的观点:

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

这是一个应处理上传文件的操作。
[HttpPost]
public ActionResult BookAdd(IEnumerable<HttpPostedFileBase> files)
{
    // some actions
    return View();
}

问题是"file"始终包含两个为空的元素。
该如何解决?

现在该是一些新闻了。看来我找到了问题,但我仍然不知道如何解决。看来,尽管事实是我在这里使用“multipart / form-data”:
@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在 Controller 中仍为“application / x-www-forum-urlencoded”。

最佳答案

只需删除输入字段名称中的方括号即可:

@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 View 中有另一个表单。这就是为什么尽管您的内部表单具有enctype="multipart/form-data"属性,但您得到了错误的Request.ContentType的原因。因此,如果您希望这样做,则必须取消嵌套这些表格。同样在您发送给我的示例中,您的BookAdd Controller 操作没有带文件列表的正确签名,但是我想这是由于您正在执行一些测试所致。

关于asp.net-mvc-3 - MVC。 HttpPostedFileBase始终为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8159725/

相关文章:

asp.net-mvc-3 - 使用 Razor 在 Telerik MVC3 网格中选择筛选器选项

jquery - 在 jquery 模板中将 &lt 渲染为文本,而不是 < 或 &gt,因为它不是 >

c# - ASP.Net MVC 将标签值回发到您的 Controller

asp.net-mvc - ModelState.IsValid 总是返回 false

javascript - Jquery 自动完成没有结果附加为下拉子问题

entity-framework - 如何使用 EF 更新 Controller 中的对象?

JQuery 验证插件 - SubmitHandler 语法

asp.net-mvc-3 - ASP.NET MVC 如何在两个同名 View (aspx 和 razor)之间进行仲裁?

asp.net - 'ModelClientValidationRule' 类型存在于两个 dll 中

c# - MembershipService.ChangePassword 不更改密码问题