开发者

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

开发者 https://www.devze.com 2022-12-24 07:15 出处:网络
I\'m trying to build up a string array in JavaScript and get the result开发者_如何学运维s in a string list in the action method.Below is what my JavaScript looks like.I\'m using jQuery 1.4.2.The probl

I'm trying to build up a string array in JavaScript and get the result开发者_如何学运维s 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#?

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:

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

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


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

Adding traditional : true in the ajax options should work.

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

        // success
    }
});


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

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消