通过 Ajax 将数组传递给 MVC Action

kuk*_*muk 4 c# asp.net ajax jquery asp.net-core-mvc

我的控制器操作有以下代码

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

{

}
Run Code Online (Sandbox Code Playgroud)

我的ajax代码如下所示

$("#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.");
  }
});
});
Run Code Online (Sandbox Code Playgroud)

在浏览器控制台中,我看到所有正确的参数,但 MVC 操作未接收参数。array.count shows 0。我在这里错过了什么?

Gio*_*sos 5

这对我来说是有效的:

jQuery ajax 方法:

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

控制器动作:

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

{
    // Add [FromBody]
}
Run Code Online (Sandbox Code Playgroud)

  • @kukamuk 我真的很高兴能够帮助你! (2认同)