我将JSON字符串发布到接受我创建的对象的控制器方法。该对象有两个属性:一个int列表和一个字符串。我想在js中创建JSON字符串,通过AJAX发布到控制器。我找不到一种在JSON中动态创建List的方法。
这是我想要构建JSON的地方
var ApplicantIDs = [];
var RejectionReason = $("#SelectedRejectReason").val();
ApplicantIDs = $("#RejectIDs").val();
var Rejection;
jQuery.each(ApplicantIDs, function(i) {
//add ApplicantIDs to Rejection object
});
//add RejectionReason to Rejection object
RejectApplicants(Rejection);
这是AJAX帖子
function RejectApplicants(Rejection) {
jQuery.ajax({
type: "POST",
url: '@Url.Action("RejectApplicants", "Home")',
data: JSON.stringify(Rejection),
dataType: "json",
contentType: "application/json",
success: function (data) {
if (data.redirectTo == null) {
window.location.href = '@Url.Action("Error", "Home")';
} else {
alert("All selected applicants exported succesfully!");
window.location.href = data.redirectTo;
}
},
error: function () {
window.location.href = '@Url.Action("Error", "Home")';
}
});
}
控制器
[HttpPost]
public ActionResult RejectApplicants(Rejection myRejection)
我的拒绝对象
public class Rejection
{
public List<int> ApplicantIDs { get; set; }
public string RejectionReason { get; set; }
}
答案 0 :(得分:1)
您可以声明对象,如下所示:
var Rejection = {
RejectionReason: $("#SelectedRejectReason").val(),
ApplicantIDs: $("#RejectIDs").val().split(',')
};
RejectApplicants(Rejection);