Ivan Apungan
Ivan Apungan

Reputation: 534

How to pass list from ajax to controller

I have a controller like so..

public ActionResult Report(List<string> invoiceIds)

and I have an ajax call like so...

function generateAccountsPayableReports() {
    var ms = $("#msInvoicesAPV").data("kendoMultiSelect");
    var invoices = ms.dataItems();
    var invoiceIds = [];

    invoices.forEach(function (invoice) {
        invoiceIds.push(invoice.Id);
    });

    //invoiceIds = JSON.stringify(invoiceIds); 
    console.log("InvoiceIds: ", invoiceIds);

    $.ajax({
        type: "GET",
        url: "/APV/Report",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(invoiceIds),
        success: function (result) {
            if (result) {
                console.log("result: ", result);
            }
        },
        failure: function (result) {
            console.error("result: ", result);
        },
        error: function (result) {
            console.error("result: ", result);
        }
    });
}

I have tried everything I could think of:

when I tried this, it passed in the controller but on a single element only..

{'invoiceIds': JSON.stringify(invoiceIds)}

It was passed on one element only

nothing seems to work... what am I doing wrong?

by the way the array in javascript are guid

how do I pass it properly?

Upvotes: 1

Views: 638

Answers (3)

Jahangir
Jahangir

Reputation: 161

You can try like this way

var ajaxData = { invoiceIds: invoiceIds };

than passing the data like this way through ajax

data: ajaxData

Upvotes: 0

Afrim Kafexholli
Afrim Kafexholli

Reputation: 114

Instead of List<string> declare an array of string in the method controller so it should look like this Report(string[] invoiceIds) and to the ajax call just bind array to data: like this data: invoiceIds

Upvotes: 0

Digital3D
Digital3D

Reputation: 161

you use type as "GET" and not "POST", use "POST" and don't change anything, normally it will work like that It seems it receive ONE string in your LIST

Upvotes: 1

Related Questions