Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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" });
    }
share|improve this question
up vote 52 down vote accepted

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
    }
});
share|improve this answer
    
Damn, I've been scratching my head for hour about this one. Thank you! – Fabzter May 22 '12 at 18:34
    
The here link is broken. – Ryan Gates Jan 18 at 3:03
    
Thanks @RyanGates, honestly I can´t remember now what was in that link. I believe this may help now. – uvita Jan 19 at 14:34
    
@uvita you're welcome. – Ryan Gates Jan 19 at 21:53

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;
share|improve this answer
    
just FYI its actually: jQuery.ajaxSettings.traditional = true; – aherrick May 12 '11 at 14:14
1  
@aherrick - fixed :) – Nick Craver May 12 '11 at 14:19
    
right on :) funny because i actually came back to this post as a reference on how to do this globally on a recent project. – aherrick May 14 '11 at 23:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.