簡體   English   中英

通過 Ajax 將數組傳遞給 MVC 操作

[英]Passing array via Ajax to MVC Action

我的 controller 操作有以下代碼

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

{

}

我的 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.");
  }
});
});

在瀏覽器控制台中,我看到所有正確的參數,但 MVC 操作沒有收到參數。 array.count shows 0 我在這里錯過了什么?

這對我有用:

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.");
   }
});

Controller 動作:

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

{
    // Add [FromBody]
}

更改您的 controller 方法簽名以接受string[]而不是List<string>

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

javascript 正在發送一個數組,而不是 .NET類型List<string>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM