5

I'm not sure why this is happening. I have a string array that should be sent to a controller action that's expecting a string array. This is my jQuery:

$.post("/@Model.Controller/@Model.Action", { "choices": ajax }, function (result) {
                $("#label" + "@Model.Id").html(result);
            });

This is my controller action:

public JsonResult UpdateMultipleType(string[] choices)
    {
        return Json(choices);
    }

I took a look in Firebug and in the Post Tab, the headers read:

Parametersapplication/x-www-form-urlencoded
choices[]   Comedy
choices[]   Thriller
choices[]   Action
choices[]   Adventure

I've debugged and confirmed that it is hitting UpdateMultipleType and that the string array "choices" is null when that action is called. The call goes through but since we're returning null, I get a Javascript error after the call completes.

I don't know why my controller action is being sent null when it's clear that there is an array called choices being sent over.

Jay Sun
  • 1,583
  • 3
  • 25
  • 33
  • [See it.](http://stackoverflow.com/questions/309115/how-can-i-post-an-array-of-string-to-asp-net-mvc-controller-without-a-form) – Tocco Jul 18 '11 at 18:31
  • Although, you can access the `choices` parameter value by using `Request["choices[]"]´ – Tocco Jul 18 '11 at 18:52

3 Answers3

12

you need to tell jQuery to use the traditional way of building ajax data.

put this in your document ready:

jQuery.ajaxSettings.traditional = true;
Patricia
  • 7,752
  • 4
  • 37
  • 70
3

Javascript:

var data = ["a", "b", "c", "d"]; //sample

//Wrap your data ...
var postData = { choices: data };

$.ajax({
    type: "POST",
    url: "/Test/Index", //Your URL here
    data: postData,
    success: function (result) {
        //your code here
    },
    dataType: "json",
    traditional: true
});

Your controller:

public JsonResult UpdateMultipleType(List<String> choices) [...]

See it.

Community
  • 1
  • 1
Tocco
  • 1,655
  • 11
  • 14
-2

You need to decorate the Action with attribute with [HttpGet] and pass the second param for Json as Allowget

[HttpGet]
public JsonResult UpdateMultipleType(string[] choices)
{
   return Json(choices, JsonRequestBehavior.AllowGet);
}

If choices are array can you change the 'Choices' to 'Choices[]'

Mangesh
  • 3,987
  • 2
  • 31
  • 52
  • That shouldn't account for why choices is null when the action is called, though. But you're right, there should be an AllowGet there. I've since added it, but, as expected, that doesn't solve my original problem. – Jay Sun Jul 18 '11 at 18:24
  • Can you change 'Choices' to 'Choices[]' – Mangesh Jul 18 '11 at 18:35
  • That didn't work. In fact, putting [HttpGet] before the action confused my Ajax call and it couldn't locate the action. – Jay Sun Jul 18 '11 at 18:52