Ajax 使用 ASP.NET MVC 6 中的文件提交表单

Ajax form submission with files in ASP.NET MVC 6

我正在使用 jquery-ajax-unobtrusive library to add in the previously existing tag helpers 快速创建一个通过 ajax 请求提交的表单。

这给了我这样的东西:

<form id="person-create" enctype="multipart/form-data" asp-controller="Person" asp-action="Create" asp-route-id="1" data-ajax="true" data-ajax-method="POST" role="form">
    <!-- There are other inputs for the other items. -->
    <input id="photo-upload" asp-for="Photo" type="file">
</form>

表单提交很好,除了我在表单中输入的文件总是带有空值。作为测试,我将表单改回不使用 ajax 并且所有内容都正确提交。我也尝试通过直接调用 jQuery 的 .ajax 函数来手动执行提交,但是,这也遇到了与使用 jquery-ajax-unobtrusive 相同的问题。

我的控制器端点如下所示:

public async Task<IActionResult> Create(int id, PersonViewModel person)
{
  // Do stuff...
}

在 PersonViewModel 中,我有一个看起来像这样的 class:

public class PersonViewModel
{
  public int PersonId { get; set; }
  public string Name { get; set; }
  public IFormFile Photo { get; set; }
}

我只是遗漏了一些明显的东西,还是在通过 Ajax 表单提交提交文件时存在本质上的不同?

根据 Stephen 的评论,jquery.unobtrusive-ajax 不能用于提交文件。相反,应该使用 jQuery .ajax() 方法和 FormData 来实现。

有关详细信息,请参阅