【问题标题】:Unable to send Form Data & File Upload via AJAX to controller无法通过 AJAX 将表单数据和文件上传发送到控制器
【发布时间】:2015-07-23 14:41:59
【问题描述】:

我正在尝试从我的视图中发送一堆表单数据并将其映射到我的控制器中的 ViewModel 参数。此外,我正在尝试使用此请求发送一个文件,该文件将映射到一个单独的参数。

formData被发送到控制器时,它正确地将文件上传映射到file参数,但是model参数属性都是空的/默认的。

总之,我的问题是:如何在发送文件的同时将表单元素值映射到控制器中的MyViewModel 参数?

型号:

public class MyViewModel
{
    public int AsssumptionSetId { get; set; }
    public int BuildingBlockId { get; set; }
    public string ReplacementCode { get; set; }
    public decimal Rounding { get; set; }
    public string DataSource { get; set; }
    public bool AER { get; set; }
    public int Term { get; set; }
}

查看:

此视图是 MyViewModel 的强类型:

<form id="buildingBlockForm">

    @Html.HiddenFor(model => model.AsssumptionSetId)
    @Html.HiddenFor(model => model.BuildingBlockId)

    @Html.TextBoxFor(m => m.ReplacementCode)

    @Html.TextBoxFor(m => m.Rounding)

    @Html.DropDownListFor(m => m.DataSource, (SelectList)ViewBag.DataSources)

    @Html.DropDownListFor(m => m.Term, (SelectList)ViewBag.Terms)

    @Html.CheckBoxFor(m => m.AER)

    <input type="file" id="file" name="file" />

    <input class="button green-button" type="submit" value="Create" />

</form>

控制器:

  public ActionResult CreateBuildingBlock(MyViewModel model, HttpPostedFileBase file)
        {
            // all of the 'model' properties = null instead of the form values
            // file = the file I chose to upload and works as expected
        }

JS:

var formData = new FormData($('#buildingBlockForm'));

// Get file and append to form data (Should only be 1)
$.each(Files["csv"], function (key, value) {
    formData .append("file", value);
});

// Send file
$.ajax({
    url: '/Assumptions/CreateBuildingBlock',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: "json",
    contentType: false,
    processData: false,

    success: function (response) {
        // Handle success
    },
    error: function (xhr, status, errorThrown) {
        // Handle errors
    }
});

【问题讨论】:

  • 这个方法还会发送文件吗?
  • 你试过新的FormData($('#buildingBlockForm')[0]);
  • new FormData($('#buildingBlockForm')[0]); 是它!谢谢!你能解释一下如何/为什么需要这样做吗?发布答案@DennisCheung,我会接受。

标签: javascript jquery asp.net-mvc ajaxform form-data


【解决方案1】:

由于您的表单包含文件输入类型,您需要您的表单来处理此提交(enctype)。

<form id="buildingBlockForm" enctype="multipart/form-data"> 

此外,如果您想坚持使用 MVC 的表单助手,它会缓解您在使用基于脚本的 ajax 帖子时可能遇到的问题。

@using (Ajax.BeginForm("CreateBuildingBlock", "Assumptions", null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "postSuccess", OnFailure = "postFailed" }, new { enctype = "multipart/form-data" }))
{
  // your form fields here
}

<script>
  function postSuccess() {
    // handle success here
  }

  function postfailed() {
    // handle failed post here
  }
</script>

【讨论】:

  • 不幸的是,问题不在于文件发布和映射到其参数,因为它工作正常。问题在于剩余的表单值没有映射到 ViewModel 对象参数。
  • 您是否按照建议的表单类型进行了尝试?我知道您在@Dennis 的建议下发布了一篇成功的帖子,但这对我来说为什么添加 [0] 解决了您的问题没有意义。
  • 是的,建议的解决方案无论有无表单类型都可以正常工作。
【解决方案2】:

原来我在抓取需要序列化的表单时缺少索引。

new FormData($('#buildingBlockForm')[0]);

这解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2017-06-22
    • 2018-06-01
    • 2016-11-15
    • 2019-12-14
    • 2016-12-15
    相关资源
    最近更新 更多