簡體   English   中英

Javascript將輸入作為數組發送到C#WebAPI

[英]Javascript send an input as array to a C# WebAPI

- - - - - - - - - - - - -編輯 - - - - - - - - - - - - --------

這不是重復的,因為我不能使用關於這個問題的ajax請求。


我正在用javascript創建一個表單來調用ac#WebApi,它將返回一個xls文件(這就是為什么我正在創建一個表單而不是ajax調用)。 webApi必須接收一個整數數組,該數組將對應於對象ID列表。 webApi是以下

[Route("getExcel")]
[HttpPost]
public HttpResponseMessage getExcel([FromBody]int[] ids)
{
...
}

我要建立的表格是這樣的:

var form = document.createElement("form");
form.setAttribute('method', "post");
setAttribute('action', baseUrl + "api/processos/getExcel");
form.setAttribute('target', "_blank");
var rows = $("#tbl").dataTable().fnGetNodes();
var arr = [];
for (var i = 0; i < rows.length; i++)
{
  ids = $("#tbl").dataTable().fnGetData(i).processosId; 
  var input = document.createElement("input");
  input.setAttribute('type', "text");
  input.setAttribute('name', "ids[]");
  input.setAttribute('value', ids);
  form.appendChild(input);
}
document.body.appendChild(form);
form.submit();

ids對的WebAPI是空的(但不是null)......當小提琴手看,原始視圖顯示了這種ids=15&ids=14&ids=13&ids=12&ids=11 ,這正是我需要的...為什么沒有關聯使用WebApi ID? 如果我的網址發送精確值(和改變[FromBody][FromUri]它的工作原理...

- - - - - - - - - -編輯 - - - - - - - - - - - - - - -

這是調用該方法時WebApi上數組ids中的內容: ids {int[0]} (在調試時看到)

因此,解決方案是在后端創建一個這樣的模型:

public class ExcelIds
{
    public int[] ids { get; set; }
}

並將控制器更改為:

[Route("getExcel")]
[HttpPost]
public HttpResponseMessage getExcel([FromBody]ExcelIds model)
{
    //code here
}

您可以使用FormDataCollection.GetValues(string Key)獲取一個字符串數組,以后可以將其轉換為int []。

[Route("getExcel")]
[HttpPost]
public HttpResponseMessage getExcel(FormDataCollection data)
{
   string[] ids = data.GetValues("ids");
   ...
}

暫無
暫無

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

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