我在控制器中得到空值.不知道我失踪了什么
我有一个网格,我有一个客人列表(名称和电子邮件),用户通过复选框选择来宾.
然后我读取所选联系人的名称和电子邮件,并构建js数组.
然后将该数组传递给MVC 3控制器.
JS代码:
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);
}
});
$.ajax({
type: "POST",url: GetURL(),data: guests,dataType: "json",success: function (res) {
//do something
}
});
控制器:
[HttpPost]
public ActionResult AddGuests(List<SelectedGuest> guests)
{
GuestService svc = new GuestService();
//do something with guests
//But Name and Email of all items in guests are null!!!
}
public class SelectedGuest
{
//represent the email columns of the contact grid
public string Email { get; set; }
//represent the Name column of the contact grid
public string Name { get; set; }
}
我需要明确地将js数组转换为json对象以将其序列化吗?
解决方法
$.ajax({
type: "POST",url: "yourUrl",data: JSON.stringify(yourArray),contentType: "application/json; charset=utf-8"
});
contentType:“application / json; charset = utf-8” – 是非常重要的部分
[HttpPost]
public void Fake(List<yourType> yourArray)
{
}