I'm trying to send a list of values from View to Controller. I tried a lot of solutions from the Internet but haven't succeeded.
My View HTML Table list of Data send to controller via JSON but the list is empty even when I use JSON.stringify
Heres my code
JavaScript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
$("body").on("click", "#btnSave", function () {
//Loop through the Table rows and build a JSON array.
var customers = new Array();
$("#tblCustomers TBODY TR").each(function () {
var row = $(this);
var customer = {};
//skill.skill_name = row.find("TD").eq(0).html();
customer.CNIC = row.find("TD").eq(1).html();
customers.push(customer);
});
console.log(customers);
console.log(JSON.stringify(customers));
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
//traditional: true,
url: "/Admin/Reconcile/Customers",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(customers),
dataType: "json",
success: function (r) {
alert(r " record(s) inserted.");
location.reload();
}
});
});
</script>
Controller Action:
public JsonResult Customers(List<String> customers)
{
}
CodePudding user response:
Firstly,you need to create a model like this:
public class Customer {
public string CNIC { get; set; }
}
Then since you pass json type data in ajax,you need to use [FromBody] in action:
public JsonResult Customers([FromBody]List<Customer> customers)
{
}
CodePudding user response:
You are sending an array of objects, so for the model binder to work you should accept a List of SomeModel, where SomeModel should have a property CNIC. Check the documentation here https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api on how objects are binded.
So you are sending this:
[
{
"CNIC":"somevalue",
"CNIC":"somevalue"
}
]
And you are trying to bind it to a List of string and it will not happen. Try binding it with List of SomeModel:
public class SomeModel
{
public string CNIC { get; set; }
}
Also try this attribute [IgnoreAntiforgeryToken] above your action. If it works then, you should be sending the antiforgery token with the post request.
