0

-------------------------EDIT--------------------------------

It's not a duplicate because I can't use an ajax Request, as asked on this question.


I'm creating a form in javascript to call a c# WebApi that will return a xls file (that's why I'm creating a form and not an ajax call). The webApi must receive an array of integer, that will correspond to a list of ids of objects. The webApi is the following

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

the form I'm building is like this:

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();

The ids on the WebApi is empty (but not null)... When watching on Fiddler, the Raw View shows this ids=15&ids=14&ids=13&ids=12&ids=11 which is exactly what I need... Why isn't associating with the WebApi ids ? If I send that exact values in the URL (and changing the [FromBody] to [FromUri] it works...

-------------------EDIT------------------------------

this is what is in the array ids on the WebApi when the method is called: ids {int[0]} (as seen while debugging)

3
  • Can you try changing name to be id[]? Commented Dec 17, 2014 at 13:25
  • it's not a duplicate because I can't use an ajax Request, it must be with a form... Commented Dec 17, 2014 at 13:40
  • changing the name doesn't affect... Commented Dec 17, 2014 at 13:43

2 Answers 2

0

So, the solution is to create a model on the backend such this:

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

and change the controller to:

[Route("getExcel")]
[HttpPost]
public HttpResponseMessage getExcel([FromBody]ExcelIds model)
{
    //code here
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could use FormDataCollection.GetValues(string Key) to get an array of strings, that you could later convert to int[].

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.