Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing IEnumerable parameter to WebAPI

I'm getting started with WebAPI and for the most part all is going well. I'm running into a problem with one particular function. This one differs from the other because it's only parameter is of type IEnumerable.

I've set a breakpoint on the first line of the Post() function and I'm hitting the function but the "values" parameter ALWAYS has a count of 0. I verified that the parameter going in on the client side does, in fact, contain an array of integers. If I remove the [FromUri] attribute, the 'values' parameter is NULL instead of a count of 0.

How do I get my array of integers to come through on my WebAPI function?

Here's the WebAPI function:

[System.Web.Mvc.HttpPost]
public void Post([FromUri] IEnumerable<int> values)
{
    if (values == null || !values.Any()) return;

    int sortorder = 1;
    foreach (int photoId in values)
    {
        _horseRepository.UpdateSortOrder(photoId, sortorder);
        sortorder++;
    }
}

Here's the AJAX call (this is using the jQuery UI Sortable feature):

$(".sortable").sortable({
    update: function (event, ui) {
                var newArray = $(".sortable").sortable("toArray");

                $.ajax({
                    url: '/api/photo',
                    type: 'POST',
                    contentType: 'application/json, charset=utf-8',
                    async: true,
                    dataType: 'json',
                    data: JSON.stringify(newArray),
                    complete: function (data) { }
                });
            }
        });
like image 611
Scott Avatar asked Jan 03 '13 23:01

Scott


1 Answers

contentType: 'application/json, charset=utf-8',

should become (the separator between the content type and the charset is a semicolon, not a comma):

contentType: 'application/json; charset=utf-8',

and:

public void Post([FromUri] IEnumerable<int> values)

should become (there are no Uri parameters in a POST request):

public void Post(IEnumerable<int> values)

Now you are good to go assuming that newArray (which you haven't shown here) is an array of integers:

newArray = [ 1, 2, 3 ]
like image 171
Darin Dimitrov Avatar answered Sep 17 '22 01:09

Darin Dimitrov