Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array via Ajax to MVC Action

I have the following code for my controller action

[HttpPost]
public async Task<IActionResult> MonthsToAdd(List<string> months)

{

}

My ajax code looks like as follows

$("#btnSave").on("click", function () {
 var months= [];
 var value = $("input[name=monthsAvailable]:checked").val()
 var lengths = $("input[value=" + value + "]").closest(".row").index()
  console.log($("input[value=" + value + "]").closest(".row").index())
  for (var i = 0; i <= lengths; i++) {
     months.push($(".outer .row:eq(" + i + ") input:radio").val())
  }

console.log(JSON.stringify(months));
$.ajax({
  contentType: 'application/json;',
  dataType: 'json',
  type: 'POST',
  url: '/AreaName/Controller/MonthsToAdd',
  data: JSON.stringify({ 'months': months}),
  success: function (response) {
     alert("success.");
  }
});
});

In the browser console I see all the correct parameters but MVC action doesn't receive the parameters. array.count shows 0. What did I miss here?

like image 773
kuka muk Avatar asked Sep 11 '25 00:09

kuka muk


1 Answers

This is what worked on my end:

jQuery ajax method:

$.ajax({
   contentType: "application/json; charset=utf-8",
   dataType: 'json',
   type: 'POST',
   url: '@Url.Action("MonthsToAdd")',
   data: JSON.stringify(months),
   success: function (response) {
       alert("success.");
   }
});

Controller action:

[HttpPost]
public async Task<IActionResult> MonthsToAdd([FromBody] List<string> months)

{
    // Add [FromBody]
}
like image 86
Giorgos Betsos Avatar answered Sep 13 '25 13:09

Giorgos Betsos