Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Ajax post is sending null to my MVC controller

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.

like image 948
Jay Sun Avatar asked Jul 18 '11 18:07

Jay Sun


Video Answer


2 Answers

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

put this in your document ready:

jQuery.ajaxSettings.traditional = true;
like image 57
Patricia Avatar answered Nov 09 '22 03:11

Patricia


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.

like image 32
Tocco Avatar answered Nov 09 '22 04:11

Tocco