开发者

Passing Array to Action from a $.post

开发者 https://www.devze.com 2023-01-22 05:56 出处:网络
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) {

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 GrantPrivilege开发者_如何学PythonsToUser(int[] privilegeIDs)       
{
    return Json(new {success=true});
}

The action sees privilegeIDs as null. Any ideas?


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: How can I post an array of string to ASP.NET MVC Controller without a form?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消