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

前端 未结 3 1853
南旧
南旧 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条回答
  • 2021-02-13 23:05

    You should use on your controller:

    public string SaveTable(object[] function_param)
    {
       //some code
    }
    

    Should do the work, it's for future users.

    0 讨论(0)
  • 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}),
    });
    
    0 讨论(0)
  • 2021-02-13 23:12

    your Ajax :

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

    in your controller:

    using Newtonsoft.Json;
    
        public string SaveTable(string function_param)
        {
           dynamic func_param = JsonConvert.DeserializeObject(function_param)
        }
    

    then you will be able to do a foreach in your controller.

    0 讨论(0)
提交回复
热议问题