C# MVC 4: Passing JavaScript array in View to Controller

前端 未结 3 1839
南旧
南旧 2021-02-13 22:24

In MVC 4, how do you pass a JavaScript array in the View to a function in the Controller with AJAX?

This doesn\'t seem the work:

$.ajax(
        {
               


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 23:07

    You need to set traditional: true when serializing arrays.

    $.ajax({
        type: "POST",
        traditional: true,
        url: "../Home/SaveTable",
        data: { function_param: countryArray }
    });
    

    Found this good explanation on what traditional: true does: https://stackoverflow.com/a/5497151/2419531

    EDIT:

    If you don't want to use traditional: true, you can pass the data as string using JSON.stringify and specifying the contentType:

    $.ajax({
        type: "POST",
        url: "../Home/SaveTable",
        contentType: 'application/json',
        data: JSON.stringify({function_param: countryArray}),
    });
    

提交回复
热议问题