文件输入不将文件上传到 MVC 操作

File Input does not upload file to MVC Action

对于一个项目,我一直在尝试将文件从我的视图上传到我的控制器操作。 但是,由于某种原因,该操作已完成,但对于该文件,我收到一个空值。

这是我的代码:

操作:

[HttpPost]
[Route("UploadSickNote")]
public ActionResult UploadSickNote(HttpPostedFileBase file)
{
    // Do something with file

    return RedirectToAction("SickNotes");
}

查看:

<form Controller="Documents" Action="UploadSickNote" method="post">
    <div>
        <input id="sicknote-upload" name="UploadedSickNote" asp-for="UploadedSickNote" type="file" accept="image/*" capture>
        <input id="sicknote-button-submit" type="submit"/>
    </div>
</form>

我也尝试过使用视图模型,但结果相同。

操作:

[HttpPost]
[Route("UploadSickNote")]
public ActionResult UploadSickNote(SickNotesViewModel vm)
{
    // Do something with file

    return RedirectToAction("SickNotes");
}

视图模型:

public class SickNotesViewModel
{
    public List<SickNoteElement> SickNoteElements { get; set; }
    public HttpPostedFileBase UploadedSickNote { get; set; }
}

我正在使用 asp.net mvc 5(不是 asp.net 核心)和一些 vue.js 用于视图功能。 非常感谢任何想法或提示。

编辑:

您必须确保您输入的名称与您的控制器匹配,因此

<input id="sicknote-upload" name="file" asp-for="UploadedSickNote" type="file" accept="image/*" capture>

如果这样做不起作用,您还可以尝试指定要发送的表单类型

<form Controller="Documents" Action="UploadSickNote" method="post" enctype="multipart/form-data">

经过更多的搜索找到了解决方案。 我现在通过将视图更改为以下方式在我的视图模型中接收文件:

   @using (Html.BeginForm("UploadSickNote", "Documents", FormMethod.Post, new { enctype = "multipart/form-data" }))
   {
            <div>
                <input id="sicknote-upload" name="UploadedSickNote" type="file" accept="image/*" capture>
                <input id="sicknote-button-submit" type="submit"/>
            </div>
   }