Search code examples
asp.netasp.net-mvcasp.net-mvc-4asp.net-web-apiasp.net-web-api-routing

pass string array as parameter to asp.net mvc webapi method


I am using webapi2 and here is my client side code

var tbody = $('#files-table').find('tbody'); // tbody where all rows exists 
        var sortOrder = $(tbody).sortable('toArray').toString(); // geting ids of all rows 
        var updateSortOrder = $.ajax({
            url: baseUrl + 'mycontroller/updateimagesorder',
            dataType: 'json',
            traditional: true,
            contentType: 'application/json',
            data: JSON.stringify({ "sortOrder": sortOrder.split(',') }),
            type: 'PUT'
        });
        updateSortOrder.done(function (result) {
            closeModel('images-model');
        });

and here is my server side method

[Route("updateimagesorder")]
    public HttpResponseMessage PutImagesSortOrder([FromBody]string[] sortOrder) 
    {
       // do stuff with parameters 
     }

Note : /mycontroller is route prefix here and baseUrl is my domain url

so , what the issue in my code ?


Solution

  • Try passing the value like this:

    data: JSON.stringify(sortOrder.split(',')),
    

    So that your request payload looks like a string array:

    ["foo", "bar"]
    

    If you want to pass the value like that:

    data: JSON.stringify({ "sortOrder": sortOrder.split(',') }),
    

    then make sure that you have declared a view model:

    public class MyViewModel
    {
        public string[] SortOrder { get; set; }
    }
    

    that your controller action will take as parameter:

    [Route("updateimagesorder")]
    public HttpResponseMessage PutImagesSortOrder(MyViewModel model) 
    {
        // do stuff with parameters 
    }