繁体   English   中英

无法通过AJAX发送表格数据和文件上传到控制器

[英]Unable to send Form Data & File Upload via AJAX to controller

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

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

总而言之,我的问题是:如何在发送文件的同时将表单元素值映射到控制器中的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
    }
});

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

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

这解决了我的问题。

由于您的表单包含文件输入类型,因此您需要使用表单来处理此提交(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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM