在嵌套JSON对象的情况下,从返回的JSON中获取数据时遇到了问题。
HTML代码如下所示:
<div>
<h2>List Employee</h2>
<br />
<table class="table table-bordered" >
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Age</td>
</tr>
</thead>
<tbody data-bind="foreach: Employees">
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Age"></td>
</tr>
</tbody>
</table>
</div>
然后击倒JS
function ProductViewModel() {
var self = this;
self.Employees = ko.observableArray();`
$.ajax({
url: '/Home/GetEmployee',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Employees(ko.mapping.fromJS(data));
}
})
}
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);`
控制器:
public JsonResult GetEmployee()
{
var employee = db.Employee.ToList();
return Json(new { data = employee }, JsonRequestBehavior.AllowGet);
}
Json对象:
`{"data":[{"Id":1,"Name":"Andrew","Age":25},{"Id":2,"Name":"John","Age":28},{"Id":3,"Name":"Layla","Age":24},{"Id":4,"Name":"Mia","Age":26}]}`
结果错误:
任何人都可以改善我的代码,请...
1条答案
按热度按时间hts6caw31#
您的
data
位于object中,因此您必须解析它:如果只需要显示数据,则无需Map即可:
self.Employees(myData.data);
个