0

I have an MVC3 controller action:

public ActionResult DoStuff(DoStuffModel model)

The DoStuffModel looks like this:

public class DoStuffModel
{
    public long SomeId { get; set; }
    public List<string> Codes { get; set; }
}

In my jQuery I do this:

 var postData = {
     SomeId: 1,
     Codes: ["code1", "code2", "code3"]
 };

$.post(url, postData, function (data) {});

The URL is correct. The postData looks like this when I log it:

enter image description here

The SomeId gets bound correctly, but Codes remains null. What is going on?

4
  • Your model expects an array called Codes, but in your dev-tools it shows that in the javascript object the array name is PiCodes. Can you check if that helps? Commented Apr 4, 2017 at 9:28
  • Just a guess, but have you tried public string[] Codes { get; set; } Commented Apr 4, 2017 at 9:29
  • Bad screenshotting on my part, sorry. The names correspond though. Commented Apr 4, 2017 at 9:29
  • please set application content-type = "application/json" Commented Apr 4, 2017 at 9:33

1 Answer 1

1

You need to use the $.ajax() method and set the correct ajax options and stringify your data.

The $.post() method is sending the data as application/x-www-form-urlencoded; charset=UTF-8, which means you would need to generate the collection with indexers in order for the DefaultModelBinder to bind it - for example

var postData = { SomeId: 1, 'Codes[0]': 'code1', 'Codes[1]': 'code2', 'Codes[2]': 'code3'};

The code using your current object containing an array would be

$.ajax({
    url: url,
    type: 'post',
    contentType: 'application/json',
    data: JSON.stringify({ model: postData })
    success: function(data) {
        ....
    }
});
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the help! However, [0].Codes does not appear to be correct syntax. My Intellisense seems to complain about it at least.
Sorry, forgot the quotes (note you can also use 'Codes[0]' in this case (collection of simple objects)
Since you are sending JSON you don't need to be using Codes[0]. The OPs original postData was correct, he was just missing the application/json header.
@DarinDimitrov, I know - I was explaining how the data would need to be generated without setting the contentType option :)
Thanks. However, neither of your options seems to work at all. Not even SomeId gets bound this way.
|

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.