35

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#?

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"
 });
}

2 Answers 2

55

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
    }
});
3
  • Damn, I've been scratching my head for hour about this one. Thank you! Commented May 22, 2012 at 18:34
  • The here link is broken. Commented Jan 18, 2017 at 3:03
  • Thanks @RyanGates, honestly I can´t remember now what was in that link. I believe this may help now. Commented Jan 19, 2017 at 14:34
7

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;
3
  • just FYI its actually: jQuery.ajaxSettings.traditional = true; Commented May 12, 2011 at 14:14
  • 1
    right on :) funny because i actually came back to this post as a reference on how to do this globally on a recent project. Commented May 14, 2011 at 23:46
  • @aherrick it always happens :D Commented Oct 23, 2019 at 4:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.