我的bootstrap datatable插件有问题我的课看起来像这样:
public class Class1 {
public string EmployeeID { get; set; }
public string FirstName { get; set; }
public Position Position { get; set; }
public Class1 GetEmployees()
{
return this;
}
}
public class Position {
public string PositionID { get; set; }
public string PositionName { get; set; }
//Other functions below
}
public JsonResult GetEmployees()
{
return Json(new Class1().GetEmployees(), JsonRequestBehavior.AllowGet);
}
<table id="tblLeaveCredits"
data-url="/Employees/GetEmployees"
data-toggle="table"
data-search="true"
data-click-to-select="true"
data-select-item-name="rdoSelectedItem"
data-cache="false">
<thead>
<tr>
<th data-field="state" data-radio="true"></th>
<th data-field="FirstName" data-sortable="true">Description</th>
<th data-field="Position.PositionName" data-sortable="true">Available</th>
</tr>
</thead>
</table>
我的问题是,如何从Json返回中获取Position类的数据并将其显示为datatable中的字段?
如上所述,似乎datatable插件没有选择将嵌套的json对象数组绑定到表。因此,我使用了客户端方法来展平嵌套的json-objects数组,以便能够将其绑定到数据表。参见我的演示将嵌套对象绑定到数据表:
$(function () {
// apply flattenJson to every item in the array and return a new array
// using jQuery.map
flattenedData = jQuery.map( data, function(d){ return flattenJson(d) });
// bind the now unnested array to the datatable
$('#table').bootstrapTable({
data: flattenedData
});
console.log(flattenedData);
});
给定这个嵌套的json对象数组:
var data = [
{
"EmployeeID": "123",
"FirstName": "Marc",
"Position": {"PositionID": 1, "PositionName": "Supermarket"}
},
{
"EmployeeID": "456",
"FirstName": "Scott",
"Position": {"PositionID": 2, "PositionName": "Googleplex"}
},
{
"EmployeeID": "789",
"FirstName": "John",
"Position": {"PositionID": 3, "PositionName": "SanFran"}
}
];
function flattenJson(data) {
var result = {};
function recurse (cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop + "[" + i + "]");
if (l == 0)
result[prop] = [];
} else {
var isEmpty = true;
for (var p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop+"."+p : p);
}
if (isEmpty && prop)
result[prop] = {};
}
}
recurse(data, "");
return result;
}
要绑定现在未嵌套的对象,您可以使用此html
<table id="table">
<thead>
<tr>
<th data-field="EmployeeID">ID</th>
<th data-field="FirstName">Firstname</th>
<th data-field="Position.PositionID">PositionID</th>
<th data-field="Position.PositionName">PositionName</th>
</tr>
</thead>
</table>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句