0

I've already done research on how to post data to MVC controllers/actions and I'm running into a bit of trouble. I wish to post data (via javascript), to my MVC Controller, in this format:

{
  someString: "thisString",
  myArray: ["string1", "string2"]
}

My MVC Action has the following signature:

[HttpPost]
public ActionResult someAction(FormCollection formValues);

If I check the values of formValues, I'll see key/value pairs:

key: "someString"
value: "thisString"

key: "myArray[]"
value: [0]: "string1", [1]: "string2"

It all looks good untill I try:

TryUpdateModel(MyCustomModel);

The key/value pair someString/"thisString" binds perfects but the array (myArray) resolves to null.

My Model looks like this:

public MyCustomModel 
{
    public string someString {get; set;}
    public string [] myArray {get; set;}
}

Here is how my post looks like (jQuery):

$.post
(
    "Controller/someAction",
    {
        someString: "thisString",
        myArray: ["string1", "string2"],
    },
    function(data) { ...do something }
); 

What on earth am I doing wrong? Does the default MVC ModelBinder not support binding a simple array of strings?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Nadir Muzaffar
  • 4,772
  • 2
  • 32
  • 48
  • 2
    if your on MVC 3, you should try posting as JSON from the JS (including stingify'ing it) – RPM1984 Aug 25 '11 at 00:01
  • lol tried that to no avail, unless i did it wrong...but thanks – Nadir Muzaffar Aug 25 '11 at 00:03
  • No probs, perhaps update your post with the JS your using to post to the action? So we can see all the parts of the flow. – RPM1984 Aug 25 '11 at 00:27
  • I've never used @spencerooni's solution. I have used `$.postify` [here](http://www.nickriggs.com/posts/post-complex-javascript-objects-to-asp-net-mvc-controllers/). You'll have to use the tweak in the comments to avoid errors being thrown on null elements, though. – Joseph Yaduvanshi Aug 25 '11 at 00:47

1 Answers1

2

You must add the following when posting to your controller action

traditional: true

I just replicated the issue on my machine and that solved it. I also found this post which seems to have contained the same solution

Edit

Here's another similar question...

Community
  • 1
  • 1
David Spence
  • 7,999
  • 3
  • 39
  • 63