How to pass a list of id's in a AJAX request to the Server in MVC How to pass a list of id's in a AJAX request to the Server in MVC ajax ajax

How to pass a list of id's in a AJAX request to the Server in MVC


Use the traditional parameter and set it to true.

$.ajax({    type: "POST",    url: "/URL",    dataType: "json",    traditional: true,    data: {}});


Try this one (I've checked it):

$(function () {        var ids = [1, 4, 5];        $.ajax({            type: 'POST',            contentType: 'application/json; charset=utf-8',            url: '@Url.Action("YourAction", "YourController")',            data: JSON.stringify( { ids: ids })        }).done(function () {        });    });

You have to make sure your contentType is application/json and your data is stringified.


public ActionResult SaveSomething(int[] requestData) //orpublic ActionResult SaveSomething(IEnumerable<int> requestData)

Using Action Result you cannot receive JSON object:

Using Controler:

[HttpPost]    [Route( "api/Controller/SaveSomething" )]    public object SaveTimeSheet( int[] requestData )    {        try        {            doSomethingWith( requestData );            return new            {                status = "Ok",                message = "Updated!"            };        }        catch( Exception ex )        {            return new            {                status = "Error",                message = ex.Message            };        }}

java script:

var ids = [1,4,5];var baseUrl: 'localhost/yourwebsite'$.ajax({                    url: baseUrl + '/api/Controller/SaveSomething',                    type: 'POST',                    data: JSON.stringify(ids),                    dataType: 'json',                    contentType: 'application/json',                    error: function (xhr) {                        alert('Error: ' + xhr.statusText);                    },                    success: function (result) {                        if (result != undefined) {                            window.location.href = window.location.href;                        }                    },                    async: false,                });