【问题标题】:Ajax form submission with files in ASP.NET MVC 6使用 ASP.NET MVC 6 中的文件提交 Ajax 表单
【发布时间】:2016-10-27 09:13:40
【问题描述】:

我正在使用jquery-ajax-unobtrusive 库添加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 中,我有一个看起来像这样的类:

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

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

【问题讨论】:

  • 尝试将与您的模型属性相同的 ID 和名称提供给 HTML 页面,然后检查
  • 您无法使用jquery.unobtrusive-ajax 提交文件。您可以使用 jQuery .ajax() 方法和 FormData,如 this answer 中所述

标签: jquery ajax asp.net-mvc asp.net-core-1.0


【解决方案1】:

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

有关详细信息,请参阅Stephen's answer on another question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 2011-07-09
    相关资源
    最近更新 更多