Passing array of integers to webapi Method

断了今生、忘了曾经 提交于 2019-11-28 11:25:13
Shashank

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.

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; }
    }

I suspect that the stringify bit is messing up your object - have you tried assigning it to a variable to see if it's the expected formatting?

You're stringifying the whole thing at the moment:

{ "deletedIds": deletedIds }

while what you probably want to send as post body is this:

{ "deletedIds": JSON.stringify(deletedIds) }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!