I am posting a JSON string to a controller method that accepts an object I created. The object has two properties: a List of ints, and a string. I want to create the JSON string in js to post to the controller via AJAX. I can't find a way to create the List dynamically in JSON though.
Here's where I want to build the 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);
Here's the AJAX post
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")';
}
});
}
Controller
[HttpPost]
public ActionResult RejectApplicants(Rejection myRejection)
And my Rejection Object
public class Rejection
{
public List<int> ApplicantIDs { get; set; }
public string RejectionReason { get; set; }
}