我正在对传递FormData()的控制器进行ajax调用,FormData()有一个对象数组以及很少的其他属性。在我的控制器中,我传递的列表数组似乎有0个元素。请帮忙!
cshtml视图中的脚本 -
var _getFormDataToJson = function () {
var applyDetail = [];
$(_tb).find('tbody tr').each(function (i, v) {
var trans = {
effectiveDate: $(this).find('.effectiveDate').val(),
amount: $(this).find('.amount').val(),
empLeaveHdID: $('#tx-leaveHdID').val(),
//attachmentUrl: $(this).find('.leaveAttachment')[0].files[0]
}
applyDetail.push(trans);
});
var formObj = new FormData();
formObj.append('remark', $('#tx-remark').val());
formObj.append('leaveAppType', $('#hdnLeaveAppType').val());
formObj.append('applyDetail', applyDetail); //this collection has 0 items in controller
return formObj;
}
var _sumbitForm = function () {
var formData2 = _getFormDataToJson();
$.ajax({
url: '@Url.Action("ApplyLeave", "Leave")',
type: 'POST',
processData: false,
contentType: false,
data: formData2,
//data: { data: formData2 },
success: function (data) {
if (data.success) {
_myToastr.success(data.msg[0], true, function () {
location.reload();
});
$(_modal).modal('close');
}
else {
_myToastr.error(data.msg[0]);
}
},
complete: function () {
}
});
}
控制器 -
[HttpPost]
public JsonResult ApplyLeave(Hr_LeaveApplyHd data)
{
foreach (var detail in data.applyDetail) //applyDetail count is 0 here
{
//to DO:
}
return new JsonResult();
}
编辑: Hr_LeaveApplyHd模型 -
public class Hr_LeaveApplyHd
{
public Hr_LeaveApplyHd()
{
applyDetail = new List<ApplyDetail>();
}
[Key]
public int applyID { get; set; }
public string remark { get; set; }
public virtual List<ApplyDetail> applyDetail { get; set; }
public LeaveAppType leaveAppType { get; set; }
}
applyDetail model -
public class ApplyDetail
{
[Key]
public int applyDetialID { get; set; }
public DateTime effectiveDate { get; set; }
public decimal amount { get; set; }
public int empLeaveHdID { get; set; }
}
答案 0 :(得分:2)
您无法将数组和/或复杂对象追加到FormData
。您需要为ApplyDetail
的每个属性以及集合中的每个项目以及索引器附加名称/值对,例如
formObj .append('applyDetail[0].effectiveDate', '09/19/2017');
您可以在$.each
循环中执行,例如
var formObj = new FormData();
formObj.append('remark', $('#tx-remark').val());
formObj.append('leaveAppType', $('#hdnLeaveAppType').val());
$(_tb).find('tbody tr').each(function (i, v) {
var name = 'applyDetail[' + i + '].effectiveDate';
var value = $(this).find('.effectiveDate').val();
formObj.append(name, value);
... // ditto for other properties
});
但是,如果您使用强类型HtmlHelper
方法正确生成了表单,包括使用for
EditorTemplate
循环为{0}类型ApplyDetail
生成集合属性的控件所以他们有正确的名称属性来匹配你的模型,然后你需要的只是
var formObj = new FormData($('form').get(0));
将正确序列化所有表单控件