通过 ajax 将 LIst 发送到复杂模型
本文关键字:复杂 模型 ajax LIst 通过 | 更新日期: 2023-09-27 17:56:06
我知道我以前做过这个,但我似乎无法让它工作。
我有以下JavaScript;
$("#btnTestVouchers").click(function () {
var postData = {
"workplaceGiverId": $(".wpgDropdownList").val(),
"fromMemberId": $(".wpgFromMemberDropdownList").val(),
"toMemberId": $(".wpgToMemberDropdownList").val(),
"voucherExpiryDate": $("#expiryDatePicker").val(),
"recipients": JSON.stringify("[{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]")
};
console.log(postData);
$.ajax({
type: "POST",
url: "/Admin/TestVoucherCreationEmails",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(postData),
success: function (d) {
alert("OK");
},
error: function (xhr, textStatus, errorThrown) {
alert("Error:" + errorThrown);
}
});
});
在我的模型中,我有;
public class postDataObject
{
public int workplaceGiverId { get; set; }
public int fromMemberId { get; set; }
public int toMemberId { get; set; }
public string voucherExpiryDate { get; set; }
public IEnumerable<BulkVoucherRecipient> recipients { get; set; }
}
public class BulkVoucherRecipient
{
public string firstname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string voucheramount { get; set; }
}
在我的控制器中,我有;
[HttpPost]
public void TestVoucherCreationEmails(postDataObject postedData)
{
string g = "";
}
但是,当我发布时,收件人列表始终为空。
如果我不字符串化收件人列表,我会得到相同的结果。
有人知道我做错了什么吗?
编辑其他值都正常,只是列表为空。
您无需JSON.stringify
收件人。
"recipients": JSON.stringify("[{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]")
在此处删除JSON.stringify
表单,它应该可以工作。
var postData = {
"workplaceGiverId": $(".wpgDropdownList").val(),
"fromMemberId": $(".wpgFromMemberDropdownList").val(),
"toMemberId": $(".wpgToMemberDropdownList").val(),
"voucherExpiryDate": $("#expiryDatePicker").val(),
"recipients": [{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]
};
试试这个,它应该可以工作
[HttpPost]
public void TestVoucherCreationEmails([FromBody]postDataObject postedData)
{
string g = "";
}