JQuery Ajax message sends null to my MVC

I am not sure why this is happening. I have a string array that needs to be sent to a controller action that expects 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 looked at Firebug and the Post tab, the headers read:

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

I debugged and confirmed that it clicks UpdateMultipleType and that the "selection" of the string array is null when this action is called. The call passes, but since we return null, I get a Javascript error after the call ends.

I do not know why my controller action is sent null when it clears, that there is an array that is called when it is sent.

+5
source share
3

jQuery, ajax.

:

jQuery.ajaxSettings.traditional = true;
+12

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

:

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

.

+3

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

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

If you select an array, you can change the "Select" to "Select []"

-2
source

All Articles