gpt4 book ai didi

javascript - 无法通过 AJAX 将表单数据和文件上传发送到 Controller

转载 作者:行者123 更新时间:2023-12-03 10:09:35 26 4
gpt4 key购买 nike

我试图从我的 View 发送一堆表单数据并将其映射到我的 Controller 中的 ViewModel 参数。此外,我正在尝试发送包含此请求的文件,该文件将映射到单独的参数。

formData 发送到 Controller 时,它会正确地将文件上传映射到 file 参数,但是 model 参数属性全部为空/默认值。

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

查看:

此 View 是 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>

Controller :

  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]);

这解决了我的问题。

关于javascript - 无法通过 AJAX 将表单数据和文件上传发送到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30195708/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com