4

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?

11
  • With { 'months': months} you are passing an object which contains months as properties. But your controller accept List so change to data: JSON.stringify(months), to pass array from js Commented Jan 9, 2021 at 7:39
  • @user1672994 Thanks, i tried that too, still the same Commented Jan 9, 2021 at 7:42
  • Is this an MVC or a Razor pages application? Commented Jan 9, 2021 at 7:43
  • I've added the relevant tag Commented Jan 9, 2021 at 7:45
  • 1
    So it's .NET core-mvc not razor-pages,i've updated the tags again Commented Jan 9, 2021 at 8:03

1 Answer 1

5

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]
}
Sign up to request clarification or add additional context in comments.

4 Comments

@kukamuk I'm really glad I was able to help you!
Nice answer! Why exactly did the [FromBody] attribute make the difference? I'm asking because I am currently working on a large mvc api, and [FromBody] is nowhere to be seen.
@ShaiCohen This is required for the model binder to work in .net core (I think 2.0 or later). A really good article on this topic can be found here.
"which you could previously do in ASP.NET 4/MVC 5." ... I'll show my dinosaur self out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.