I am getting null values in the controller. Not sure what am I am missing.
I have a grid where I have a list of guests (with name & email) where user select gues
You get null because you're sending the json array in wrong way.
First, you should serialize your json array:
$.ajax({
// Whatever ...
type: "POST",
url: "yourUrl",
data: JSON.stringify(guests),
// Whatever ...
});
Second, your controller should get a string:
[HttpPost]
public ActionResult ActionName(string guests)
{
// ...
}
and finally, you should deserialize that string to the related type:
[HttpPost]
public ActionResult ActionName(string guests)
{
// this line eserializes guests ...
IList<GuestType> gs =
new JavaScriptSerializer().Deserialize<IList<GuestType>>(guests);
// ... Do whatever with gs ...
return View();
}
just set the 'traditional:true" in your ajax.
Example :
$.ajax({
type: "POST",
url: GetURL(),
data: PostData ,
dataType: "json",
traditional:true,
success: function (res) {
//do something
}
});
If you have the liberty of using a plugin, try jQuery-JSON:
var guests = new Array();
// push stuff into the array
$.ajax({
type: "POST",
url: GetURL(),
data: $.toJSON(guests),
dataType: "json",
success: function (res) {
//do something
}
);
$.ajax({
type: "POST",
url: "yourUrl",
data: JSON.stringify(yourArray),
contentType: "application/json; charset=utf-8"
});
contentType: "application/json; charset=utf-8" - is very important part
[HttpPost]
public void Fake(List<yourType> yourArray)
{
}
Maybe changing setting traditional to true might help. Here is (modified) code that I used to post unique identifiers (Guids) to the controller action.
var yourArray = new Array();
// TODO: fill array with ids of checked checkboxes
$('.CBC:checked').each(function () {
yourArray.push($(this).attr('myId'));
});
var postData = {
yourArray: yourArray
};
$.ajax({
type: "POST",
url: "/ctrl/ActionName",
data: postData,
success: function (result) {
},
datatype: "json",
traditional: true
});
In the controller I have following action.
[HttpPost]
public ActionResult ActionName(List<Guid> yourArray)
{
return View();
}
I tried this, its working.
var name ='', email='';
var guest = new Array();
var guests = new Array();
$('.CBC').each(function () { //loop grid by checkbox class
if (this.checked) {
name = GetSelectedName();
email = GetSelectedEmail();
guest = { 'Email': email, 'Name': name };
guests.push(guest);
}
});
var PostData = { guests: guests }; //if this is creating ambiguity try using something:guest //(something is //controller parameter, change your controller parameter accordingly)
$.ajax({
type: "POST",
url: GetURL(),
data: PostData ,
dataType: "json",
success: function (res) {
//do something
}
});
Cheers,
Srinivas