C#MVC 4:将View中的JavaScript数组传递给Controller

Red*_*ces 12 javascript c# ajax asp.net-mvc json

在MVC 4中,如何将View中的JavaScript数组传递给使用AJAX的Controller中的函数?

这似乎不起作用:

$.ajax(
        {
            type: "POST",
            url: "../Home/SaveTable",
            data: { function_param: countryArray }
        });
Run Code Online (Sandbox Code Playgroud)

问题是,countryArray是JavaScript视图中的全局数组,我在传递之前检查它是否包含元素.但是,当saveTable函数接收到数组时,该函数表示它收到了一个空字符串[]数组.

我只知道将数组从Controller传递给View,您可以将复杂数据类型序列化return Json(data, JsonRequestBehavior.AllowGet);,然后通过将其设置为"var"变量对其进行反序列化.

所以我可能也必须这样做,但如何?

编辑1:

这是SaveTable函数的缩短版本:

public string SaveTable(string[] function_param)
{
    if (function_param != null && function_param > 0)
    {
       //some code                
       return "Success";
    }

    //The following code will run if it's not successful. 
    return "There must be at least one country in the Region.";
    //Yeah it's always returning this b/c function_param is null;         
 }
Run Code Online (Sandbox Code Playgroud)

Sar*_*ana 22

您需要traditional: true在序列化数组时进行设置.

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

找到了这个很好的解释traditional: true:https://stackoverflow.com/a/5497151/2419531

编辑:

如果您不想使用traditional: true,可以使用JSON.stringify并指定以下内容将数据作为字符串传递contentType:

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

  • 无论如何,它没有用,该函数仍在获取null字符串[]数组。 (2认同)