Search code examples
javascriptjqueryasp.netajaxasp.net-web-api

Pass string array as data in jquery ajax to web api


I am trying to pass string array to a Web Api method which accepts an array of strings as argument. Bellow my Web Api method

    [HttpGet]
    public string HireRocco(string[] hitList)
    {
        string updateList = string.Empty;
        return updateList;
    }

My ajax

var uri = 'http://localhost:16629/api/AssassinApi/HireRocco',
hitList = ['me', 'yourself'];

$.ajax({
    url: uri,
    type: 'GET',
    data: { hitList : hitList },
    cache: false,
    dataType: 'json',
    async: true,
    contentType: false,
    processData: false,
    success: function (data) {
    },
    error: function (data) {
    }
});

The above ajax successfully hits the HireRocco method but hitList param is still null. What should I change to pass an array of strings as param.


Solution

  • If you need to send data via a HttpGet, you can add [FromUri] you can edit your controller action as follows and your JavaScript should work as is:

    [HttpGet]
    public string HireRocco([FromUri] string[] hitList)
    {
        string updateList = string.Empty;
        return updateList;
    }