我在控制器中得到空值。不知道我是什么我失踪了。
我有一个网格在那里我有嘉宾名单(含姓名和放大器;电子邮件)。其中,用户选择客户通过复选框
然后我读的姓名和选定的联系人的电子邮件,并建立JS数组。
然后这个数组传递给 MVC 3控制器
。
JS code:
VAR名称='',电子邮件='';
VAR客=新的Array();
VAR客人=新的Array();
$('。CBC)。每个(函数(){//循环电网通过复选框类
如果(this.checked){
名称= GetSelectedName();
电子邮件= GetSelectedEmail();
客人= {电子邮件:电子邮件,名称:名称};
guests.push(客);
}
});
$阿贾克斯({
键入:POST,
网址:的GetURL()
数据:嘉宾,
数据类型:JSON,
成功:函数(RES){
//做一点事
}
});
控制器:
[HttpPost]
公众的ActionResult AddGuests(名单< SelectedGuest>客人)
{
GuestService SVC =新GuestService();
//做一些与客人
//但姓名和电子邮件的客人所有项目都空!
}
公共类SelectedGuest
{
//重新present接触电网的电子邮件列
公共字符串电子邮件{获得;组; }
//重新present接触电网的名称列
公共字符串名称{;组; }
}
我是否需要JS数组明确地转换成JSON对象序列化呢?
解决方案 $。阿贾克斯({
键入:POST,
网址:yourUrl
数据:JSON.stringify(yourArray)
的contentType:应用/ JSON的;字符集= UTF-8
});
的contentType:应用/ JSON的;字符集= UTF-8 - 是很重要的部分。
[HttpPost]
公共无效假(名单< yourType> yourArray)
{
}
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 guest by checkbox.
Then I read name and emails of the selected contacts and build js array.
Then this array is passed to MVC 3 controller
.
JS code:
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
}
});
Controller:
[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; }
}
Do I need to explicitly convert js array to json object to serialize it?
解决方案$.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)
{
}