views:

44

answers:

3

I am having trouble passing my array via a $.post.

The Javascript

var privIDs = [1,2,4,5];
$.post("/Home/GrantPrivilegesToUser", { privilegeIDs: privIDs }, function (data) {
     alert("Data Loaded: " + data.success);
});  

The Action

public ActionResult GrantPrivilegesToUser(int[] privilegeIDs)       
{
    return Json(new {success=true});
}

The action sees privilegeIDs as null. Any ideas?

+1  A: 

I use JSON to pass data as a string using the JSON2 library: http://www.json.org/js.html

var privIDs = [1,2,3,4,5];
var data = JSON.stringify({privilegeIDs : privIDs});
$.POST("/Home/GrantPrivilegesToUser", data, function (data) {
   alert("Data Loaded: " + data.success);
});

And the action would use the WebMethod type:

[WebMethod]
public object Entry_GetFormOptions(string privilegeIDs)
{
   return new {success=true};
}

There are both built-in and 3rd party functions for parsing the received JSON to access the privilege IDs.

Let me know if this does or does not help.

Fosco
+1  A: 

You need to set jQuery.ajaxSettings.traditional = true; for you jQuery ajax setting. In jQuery 1.4 they changed the way items are serialized in a form post.

please see:

http://forum.jquery.com/topic/nested-param-serialization

And: http://stackoverflow.com/questions/309115/how-can-i-post-an-array-of-string-to-asp-net-mvc-controller-without-a-form/2527206#2527206

Mark
A: 

This is what I ended up doing. Might be helpful to someone...

var privIDs = [1,2,4,5];

$.ajax({
     type: "POST",
     url: "/Home/UpdatePrivileges",
     data: { privilegeIDs: privIDs },
     traditional: true,
     success: function (json) {
          alert(json.success);
     }
});

If you use .ajax instead of .post you can include traditional: true

Blankasaurus