jQuery JavaScript 字符串数组的 AJAX 发布到 JsonResult 作为 List<string> 总是返回 Null?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2515773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:40:50  来源:igfitidea点击:

AJAX Post of JavaScript String Array to JsonResult as List<string> Always Returns Null?

jqueryasp.net-mvcajaxarraysjson

提问by aherrick

I'm trying to build up a string array in JavaScript and get the results in a string list in the action method. Below is what my JavaScript looks like. I'm using jQuery 1.4.2. The problem is my List in the action method is always showing NULL. Will a JavaScript string array not map correct to a string list in C#?

我正在尝试在 JavaScript 中构建一个字符串数组,并在 action 方法的字符串列表中获取结果。下面是我的 JavaScript 的样子。我正在使用 jQuery 1.4.2。问题是我的操作方法中的 List 总是显示为 NULL。JavaScript 字符串数组不会正确映射到 C# 中的字符串列表吗?

var test = ['test1', 'test2'];
var parms = {
  var1: 'some string',
  var2: test
};

$.ajax({
  type: "POST",
  url: "/Test/JSONTestAction",
  async: false,
  data: parms,
  dataType: "json",
  success: function(data) {

    // success
  }
});

Then my JsonResult looks like the following:

然后我的 JsonResult 如下所示:

public JsonResult JSONTestAction(string var1, List <string> var2) {
 // var2 is always NULL -- not good

 return Json(new {
  test = "test"
 });
}

回答by uvita

I faced the same problem after updating to jquery 1.4.2. You can find the solution here(in the Ajax section).

更新到 jquery 1.4.2 后,我遇到了同样的问题。您可以在此处找到解决方案(在 Ajax 部分)。

Adding traditional : true in the ajax options should work.

在 ajax 选项中添加传统的 : true 应该可以工作。

$.ajax({
    type: "POST",
    traditional: true,
    url: "/Test/JSONTestAction",
    async: false,
    data: parms,
    dataType: "json",
    success: function(data) {

        // success
    }
});

回答by Nick Craver

This change was to make native behavior better for PHP/Rails users, you can read about the params changes more here.

此更改是为了使 PHP/Rails 用户的本机行为更好,您可以在此处阅读有关参数更改的更多信息

You can enable it per-request like this:

您可以像这样按请求启用它:

$.ajax({ 
 //Stuff...
 traditional:true 
});

Or globally like this (only need to run once before firing any requests):

或者像这样全局(只需要在触发任何请求之前运行一次):

jQuery.ajaxSettings.traditional = true;