Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?

I accept with or without use of Html helpers.

I know MVC's model binder has no problem when it comes to simple types like int, string and bool.

Is it something like I have to use and array instead in the action?

I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server. My List ids gives null at the moment.

Javascript:

var ids= [1,4,5];
// ajax request with ids..

MVC Action:

public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
    // build model ect..
    return PartialView(model);
}

EDIT: Added my AJAX request

$(document).ready(function () {
    $('#spanComputerPackagesBuffer').on('click', function () {
        var ids = $('#divComputerPackagesBuffer').data('buffer');
        console.log('bufferIds: ' + bufferIds);
        var data = {
            ids: ids
        };

        var url = getUrlShowComputerPackageBuffer();
        loadTable(url, "result", data);
    });
});

// AJAX's
function loadTable(url, updateTargetId, data) {
    var promise = $.ajax({
        url: url,
        dataType: "html",
        data: data
    })
    .done(function (result) {
        $('#' + updateTargetId).html(result);
    })
    .fail(function (jqXhr, textStatus, errorThrown) {
        var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
        alert(errMsg);
    });
};

// URL's
function getUrlShowComputerPackageBuffer() {
    return '@Url.Action("ShowComputerPackageBuffer", "Buffer")';
};

SOLUTIONS: // Thanks to @aherrick comment. I missed the good old "traditional"

$.ajax({
    type: "POST",
    url: '@Url.Action("ShowComputerPackageBuffer", "Buffer")',
    dataType: "json",
    traditional: true,
    data: {
        bufferIds: bufferIds
    }
});
like image 377
radbyx Avatar asked Mar 04 '15 13:03

radbyx


People also ask

How pass data from controller view using AJAX in MVC?

There is no such thing as passing a data from controller via ajax. You can pass a data with ajax only from the View to the Controller. It is used in cases of SPA functionality. If you want to load data and display it in the view you should use view model in MVC and load it directly in your view.


3 Answers

Use the traditional parameter and set it to true.

$.ajax({
    type: "POST",
    url: "/URL",
    dataType: "json",
    traditional: true,
    data: {}
});
like image 157
aherrick Avatar answered Oct 23 '22 05:10

aherrick


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.

like image 32
MacGyver Avatar answered Oct 23 '22 06:10

MacGyver


public ActionResult SaveSomething(int[] requestData) 
//or
public 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,
                });
like image 1
SilentTremor Avatar answered Oct 23 '22 05:10

SilentTremor