簡體   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