Eunyoung Ro
Eunyoung Ro

Reputation: 131

Post array of strings to web API method

this is my client side ajax call:

    var list = ["a", "b", "c", "d"];

    var jsonText = { data: list };

    $.ajax({
        type: "POST",
        url: "/api/scheduledItemPriceStatus/updateStatusToDelete",
        data: jsonText,
        dataType: "json",
        traditional: true,
        success: function() { alert("it worked!"); },
        failure: function() { alert("not working..."); }
    });

this is chrome network header:

Request URL:http://localhost:2538/api/scheduledItemPriceStatus/updateStatusToDelete

Request Method:POST

Request Headersview source

Accept:application/json, text/javascript, */*; q=0.01

Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3

Accept-Encoding:gzip,deflate,sdch

Accept-Language:en-US,en;q=0.8

Connection:keep-alive

Content-Length:27

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

Host:localhost:2538

Origin:http://localhost:2538

Referer:http://localhost:2538/Pricing/ScheduledItemPrices

User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11

X-Requested-With:XMLHttpRequest

Form Dataview URL encoded

data:a
data:b
data:c
data:d

this is my webapi controller method:

public HttpResponseMessage UpdateStatusToDelete(string[] data)

result:

when I debug, the data parameter in UpdateStatusToDelete returns {string[0]} instead of data:a data:b data:c data:d

What am I doing wrong? Any help is really appreciated.

Upvotes: 11

Views: 43382

Answers (7)

jramm
jramm

Reputation: 821

You can also do this with JSON.stringify, which feels more semantically intuitive than putting things in an object with an empty string key. (I am using Web API 2, not sure if that matters.)

Client code

$.ajax({
    type: 'POST', //also works for PUT or DELETE
    url: '/api/UserRole',
    contentType: "application/json",
    data: JSON.stringify(["name1", "name2"])
})

Server Code

[HttpPost]
[Route("api/UserRole")]
public IHttpActionResult AddUsers(string[] usernames)

Upvotes: 0

Stelian Matei
Stelian Matei

Reputation: 11623

In the backend, you could use FormDataCollection.GetValues(string key) to return an array of strings for that parameter.

public HttpResponseMessage UpdateStatusToDelete(FormDataCollection formData) {
    string[] data = formData.GetValues("data");
    ...
}

Upvotes: 1

Sergey
Sergey

Reputation: 1

Setting the dataType won't help you.

This is how I do it :

var SizeSequence = {};
SizeSequence.Id = parseInt(document.querySelector("dd#Sequence_Id").textContent);
SizeSequence.IncludedSizes = [];
var sizes = document.querySelectorAll("table#IncludedElements td#Size_Name");
// skipping the first row (template)
for (var i = 1, l = sizes.length ; i != sizes.length ; SizeSequence.IncludedSizes.push(sizes[i++].textContent));

$.ajax("/api/SizeSequence/" + SizeSequence.Id, { 
     method: "POST",
     contentType: "application/json; charset=UTF-8",
     data: JSON.stringify(SizeSequence.IncludedSizes), 
...

The Server Part

// /api/SizeSequence/5
public async Task<IHttpActionResult> PostSaveSizeSequence(int? Id, List<String> IncludedSizes)
    {
        if (Id == null || IncludedSizes == null || IncludedSizes.Exists( s => String.IsNullOrWhiteSpace(s)))
            return BadRequest();
        try
        {

            await this.Repo.SaveSizeSequenceAsync(Id.Value, IncludedSizes );
            return Ok();
        }
        catch ( Exception exc)
        {
            return Conflict();
        }
    }

References

jQuery.ajax()

Upvotes: 0

Gaurav Shah
Gaurav Shah

Reputation: 343

use the method above to send array as suggested by cris in your jquery ajax call. JSON data is usually in key value pair.

  var tmp = [];
  tmp.push({
  //this is the key name 'a'  "a": "your value", //it could be anything here in 
   //string format.
    "b": "b",
    "c": "c",
    "d": "d"
   });

 { data: JSON.stringify(tmp);} 

You can also accomplish above by using two dimensional array

Additionally do this in the webapi project.

under the models folder in your web api project create a class file. Possibly class1.cs.

Create 4 properties

public string a {get; set;}
public string b {get; set;}
public string c {get; set;}
public string d {get; set;}

Now do this in your controller

using projectname.models

[HttpPost]
public return-type actionname(List<Class1> obj)
{
  //Further logic goes here
} 

I am sure this will work.

Upvotes: 0

Shaulian
Shaulian

Reputation: 427

You should pass the list itself, and not any other object wrapping it.

E.g. pass the following:

var list = ["a", "b", "c", "d"];

in

$.ajax({
        type: "POST",
        url: "/api/scheduledItemPriceStatus/updateStatusToDelete",
        // Pass the list itself
        data: list, 
        dataType: "json",
        traditional: true,
        success: function() { alert("it worked!"); },
        failure: function() { alert("not working..."); }
    });

Your method signature on server is correct.

Upvotes: 4

Mark Berryman
Mark Berryman

Reputation: 929

For passing simply types, the data to post must take the form of a name value pair with the name portion being an empty string. So you need to make the Ajax call like so:

$.ajax({
  type: "POST",
  url: "/api/values",
  data: { "": list },
  dataType: "json",
  success: function() { alert("it worked!"); },
  failure: function() { alert("not working..."); }
});

Additionally, on your Web API action, annotate it w/ the [FromBody] attribute. Something like:

public void Post([FromBody]string[] values)

That should do the trick.

Upvotes: 34

Cris
Cris

Reputation: 13351

use var jsonText = { data: JSON.stringify(list)}

Upvotes: 2

Related Questions