ajax PUT不传输数组



我在我的网页中使用javascript将GUID(url参数(+GUID数组发送到Web服务。但是当我尝试发送 GUID 数组时,参数每次都保持为空。

我的Javascript看起来像这样:

//Save Button is clicked
function saveBtnClicked() {
    var currentDataSetGuid = $("#currentDataSetGuid").val();
    var Table = $("#Table").find("tbody").first();
    var selectedElements = Table.find("input:checked");
    var saveGuidArray = new Array();
    var i = 0;
    while (i < selectedElements.length) {
        var trid = selectedElements[i].parentElement.parentElement.id;
        saveGuidArray.push(trid);
        i = i + 1;
    }
    putSave(currentDataSetGuid,saveGuidArray)
}
//Save action to call the controller
function putSave(currentDataSetGuid, saveGuidArray) {
    $.ajax({
        dataType: "json",
        cache: false,
        method: "PUT",
        url: "/api/myAPP/SaveEndpoint/" + currentDataSetGuid,
        contentType: "application/json",
        data: JSON.stringify({ paramName: saveGuidArray}),
        success: function (result) {
            showSuccess("Save was successfull");
        },
        error: function (error) {
            showError("Error while saving");
        }
    });
}

我也试过 - 但结果相同:

data: JSON.stringify(saveGuidArray),

这是我对控制器接口 (C#( 的实现

    [HttpPut]
    [Route("/api/myAPP/SaveEndpoint/{currentDataSetGuid}")]
    public IActionResult SaveAction(Guid currentDataSetGuid, List<Guid> saveGuidArray)

在我的控制器中,每次都正确设置当前DataSetGuid。 但是saveGuidArray是空的/没有元素。

我现在解决了错误。问题是作为HTTP Body的纯数据类型。

我添加了一个新类并相应地实现了控制器。

[HttpPut]
[Route("/api/myAPP/SaveEndpoint/{currentDataSetGuid}")]
public IActionResult SaveAction(Guid currentDataSetGuid, [FromBody] ViewSaveGuid saveGuidArray)

然后我在javascript中设置对象以将其作为JSON传递。字符串化

var GuidList{
   array: saveGuidArray
};
[...]
data: JSON.stringify(GuidList);

假设您的操作定义如下:

[HttpPut]
[Route("/api/myAPP/SaveEndpoint/{currentDataSetGuid}")]
public IActionResult SaveAction(Guid currentDataSetGuid, [FromBody]List<Guid> saveGuidArray)

然后,您的 Ajax 请求应按以下方式格式化:

function putSave(currentDataSetGuid, saveGuidArray) {
  if (!currentDataSetGuid || !saveGuidArray) {
    console.log('Error');
    // Handle validation
    return;
  }
  $.ajax({
      dataType: "json",
      cache: false,
      method: "PUT",
      url: "/api/myAPP/SaveEndpoint/" + currentDataSetGuid,
      contentType: "application/json",
      data: JSON.stringify({ saveGuidArray }), // Take note of the difference on this line.
      success: function (result) {
          showSuccess("Save was successfull");
      },
      error: function (error) {
          showError("Error while saving");
      }
  });
}

最新更新