简体   繁体   中英

IEnumerable array is always null…WebAPI

I'm building a comma separated string and passing it to my WebAPI method like so:

var projectids="";
                    for (var i = 0; i < chk.length; i++) {
                        projectids += chk[i].VMIProjectId + ",";
                    }
                   //projectids = "1,2,3"
                    $.ajax({
                        type: 'POST',
                        url: "http://localhost:52555/device/6/AddProjectsToDevice",
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        data: JSON.stringify(projectids),
                        success: function (msg) {
                        },
                        error: function (data) {
                            debugger;
                        }
                    });

I 'm reaching the WebApi method successfully, but my IEnumerable array projectIds is always null. Here's the method:

 [HttpPost]
   [Route("device/{deviceId}/AddProjectsToDevice")]
   public IEnumerable<VMI_DeviceLinkedProject> AddProjectsToDevice([FromUri]long deviceId,[FromBody] IEnumerable<long> projectIds){}

How do i pass my comma separated list of ids to my WebAPI method? Thanks for reading

Right now your controller action is getting a comma separated string of numbers and not a JSON array ( "[1,2,3,4]" ), which is why the model binder isn't working:

var projectids = [];
for (var i = 0; i < chk.length; i++) {
    projectids.push(chk[i].VMIProjectId);
}

And then the stringified array should bind to the IEnumerable<long> properly.

Instead of passing it as a csv value you can pass it as an array using the same code as below,

var projectIdList =[];

for (var i = 0; i < chk.length; i++) {
   projectIdList.push(chk[i].VMIProjectId);
}

Similarly change the parameter name in api method also as projectIdList and pass it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM