简体   繁体   中英

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:

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

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

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

它仅在一个元素上传递

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

by the way the array in javascript are guid

how do I pass it properly?

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

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

You can try like this way

var ajaxData = { invoiceIds: invoiceIds };

than passing the data like this way through ajax

data: ajaxData

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM