如何在asp.net mvc中绑定数组json
本文关键字:绑定 数组 json mvc net asp | 更新日期: 2023-09-27 18:27:18
我有一个包含学生信息的表,应该以json格式的数组发布到服务器这是
<table id="temlTbl">
<tr>
<th>ID</th>
<th>Name</th>
<th>Family</th>
<th>Type</th>
</tr>
<tr>
<td>1</td>
<td>ali</td>
<td>alavi</td>
<td>one</td>
</tr>
<tr>
<td>1</td>
<td>reza</td>
<td>rezaiee</td>
<td>two</td>
</tr>
</table>
这是jquery代码,用于序列化数据和post-ajax方法:
$(SaveTeacherBook).click(function () {
var students;
var jsonobj = [];
var item = {};
var Type;
for (var i = 1 ; i < temp.rows.length; i++) {
item["ID"] = temp.rows[i].cells[0].innerHTML;
item["Name"] = temp.rows[i].cells[1].innerHTML;
item["Family"] = temp.rows[i].cells[2].innerHTML;
switch (temp.rows[i].cells[3].innerHTML) {
case "One":
Type= "1";
break;
case "Two":
Type= "2";
break;
case "Three":
Type= "3";
break;
}
item["Type"] = Type;
jsonobj.push(item);
}
students= JSON.stringify(jsonobj);
$.post('@Url.Action("Student", "Home")', students);
});
这是我的行动方法:
[HttpPost]
public ActionResult NewTeacherBook( IList<ViewModel.StudentViewModel> students)
{
...
}
型号:
class StudentViewModel
{
public string ID {get; set;}
public string Name {get; set;}
public string Family {get; set;}
public string Type {get; set;}
}
这是json格式的数据:
"[{"ID":"1","Name":"ali","Family":"alavi","Type":"1"},{"ID":"2","Name":"reza","Family":"rezaiee","Type":"2"}]"
我试图发布json数组对象,但没有绑定到控制器中,有人能帮我吗?
我认为您必须反序列化到操作中的对象
[HttpPost]
public ActionResult NewTeacherBook( string students)
{
IList<ViewModel.StudentViewModel> = new JavaScriptSerializer().Deserialize<IList<ViewModel.StudentViewModel>>(students);
}
您的开关似乎坏了。您在第二个和第三个case语句中指定的属性名称是day,但在第一个case语句中将其指定给Type(考虑到您的模型,这看起来很正确)。我不确定这是否会导致模型绑定器忽略您的对象并拒绝绑定,但这是一个很好的第一步。
switch (temp.rows[i].cells[3].innerHTML) {
case "One":
Type= "1";
break;
case "Two":
day = "2";
break;
case "Three":
day = "3";
break;
}
为了让模型绑定器正确处理ajax请求,该请求需要将内容类型指定为application/json; charset=utf-8
尝试更改以下内容的$.post...
行:
$.ajax({
url: '@Url.Action("Student", "Home")',
data: students,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'post',
success: onSaved,
error: onError
});
我将jquery代码更改为:
$(SaveTeacherBook).click(function () {
...
students= JSON.stringify({"students":jsonobj});
$.ajax({
url: '@Url.Action("Student", "Home")',
type: "POST",
data: students,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
});
动作方式:
[HttpPost]
public ActionResult NewTeacherBook( IList<ViewModel.StudentViewModel> students)
{
...
}
通过此更改,正确绑定