Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array of integers to webapi Method

I am trying to pass an array of int but I can not get the value in the webapi method

var postData = { "deletedIds": deletedIds };

    $.ajax({
        type: "DELETE",
        traditional: true,
        dataType: 'json',
        contentType: 'application/json',
        cache: false,
        url: "/api/Management/Models",
        data: JSON.stringify(postData),
        success: ModelDeleted,
        error: ModelNotDeleted
    });

and in apiController :

[HttpDelete]
        public bool DeleteModel(int[] deletedIds)
        {
            return modelsRepository.DeleteModels(deletedIds);
        }
like image 562
Muhammad Alaa Avatar asked May 04 '13 13:05

Muhammad Alaa


2 Answers

Your code looking pretty Ok to me. Please define structure of "deletedIds" object. one suggestion is to Use new Array() object to initialize deletedIds property and remove JSON.stringify() . A similar question asked here.

EDIT

Web API supports parsing content data in a variety of ways, but it does not deal with multiple posted content values. A solution for your problem could be to create a ViewModel with a property of int[] type. Like code below,

public class SimpleViewModel
{
    public int[] deletedIds{ get; set; }
}

//Controller
[HttpDelete]
    public bool DeleteModel(SimpleViewModel deletedIds)
    {
        return modelsRepository.DeleteModels(deletedIds.deletedIds);
    }

and use it as parameter type.

like image 77
Shashank Avatar answered Nov 19 '22 00:11

Shashank


At last, based on @Shashank Answer it worked and the code modified as :

var deletedIds = new Array();

deletedIds.push(modelId);

var postData = { "DeletedIds": deletedIds };
$.ajax({
    type: "Delete",
    traditional: true,
    dataType: 'json',
    cache: false,
    url: "/api/Management/Models",
    data: postData,
    success: ModelDeleted,
    error: ModelNotDeleted
});

and the apiController :

[HttpDelete]
        public bool DeleteModels(DeleteViewModel dvm)
        {
            return modelsRepository.DeleteModels(dvm.DeletedIds);
        }

and for the DeleteViewModel :

public class DeleteViewModel
    {
        public int[] DeletedIds { get; set; }
    }
like image 22
Muhammad Alaa Avatar answered Nov 18 '22 23:11

Muhammad Alaa