Jquery $.ajax() call to pass associative array with other params to MVC controller failing
I have a generic dispatcher that takes in parameters and then make $.ajax() As you can see, I am looping through the parameters to build the data.
function dispatch(controller, action, param1, param2,...) {
var args = '', pg = 1, id = '';
var l = arguments.length;
var data = {};
for (var i = 2; i < arguments.length; i += 2) {
data[arguments[i]] = arguments[i + 1];
}
$.ajax({
type: "POST",
url: "/" + (controller + "/" + action,
data: data,
dataType: "json",
success: function (res) {
alert('success');
},
error: function (xhr, status, error) {
开发者_开发问答 alert('error!');
}
});
}
This is how I call:
dispatch("XYZ", "AddGuests", "id", 10, "name", "Bob");
Everything works as expected and I get all parameters back in my MVC 3 controllers. Now I need to pass multidimentional associative array as parameter to my controller. I want to use the single generic dispatcher I use for other calls. But somehow I am getting null for the associative array parameter.
Basically I want to post a guests array to my controller's List parameter.
Code to prepare the associative array data:
var guest = {};
var guests = [];
for(var i=0;i<2;i++){
var name = GetName();
var email = GetEmail();
guest = { 'Email': email, 'Name': name };
guests.push(guest);
}
End of the loop would give me, say:
{
{'Email':"bob@zyz.com", 'Name':"Bob"},
{'Email':"tom@zyz.com", 'Name':"Tom"}
}
This is the new call to the dispatcher:
dispatch("XYZ", "AddGuests", "id", 10, "guests", JSON.stringify(guests));
This is my controller:
[HttpPost]
public ActionResult AddGuests(string id, List<SelectedGuest> guests){
//save guests
}
[Serializable]
public class SelectedGuest
{
public string Email { get; set; }
public string Name { get; set; }
}
When I look at httpfox I see correct values posted:
id 10
guests [{"Email":"bob@zyz.com","Name":"Bob"},{"Email":"tom@zyz.com","Name":"Tom"}]
If I do this, I get the guest passed correctly to my controller: But this limits me to pass just the guests array not other parameters.
data = JSON.stringify(guests);
What I am doing wrong? Thanks for reading.
If using JSON.stringify(guests) works, why not combine it into another JSON object with your other parameters that don't need stringification?
data = { "id": 10, "Guests": JSON.stringify(guests) };
Alternatively, you could construct a javascript object that combines these and call stringify on that.
精彩评论