我想利用http://www.datatables.net/examples/api/row_details.html
所示的子行功能,但我对绑定现有的System.Data.Datatable没有兴趣。
HomeController.cs
public DataTable GetData(string sql, string connectionString)
{
var tbl = new DataTable();
try
{
var sqlConnection = new SqlConnection(connectionString);
using (sqlConnection)
{
var sqlDataAdapter = new SqlDataAdapter(sql, sqlConnection);
using (sqlDataAdapter)
{
sqlDataAdapter.Fill(tbl);
}
}
}
catch (Exception)
{
}
return tbl;
}
var sql = "SELECT [Title], [Firstnames], [Surname], [Address1], [Address2], [Postcode], [PhoneNumber], [CustomerNumber], [System] FROM [OurDb]
using (var tbl = GetData(sql, MyConnection))
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var rows = (from DataRow dr in tbl.Rows select tbl.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName, col => dr[col])).ToList();
ViewBag.AjaxDataTable = serializer.Serialize(rows);
}
_Layout.cshtml
$(document).ready(function () {
var table = $('#example').DataTable({
"pagingType": "full",
"iDisplayLength": 5,
"aLengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"ajax": "@Html.Raw(ViewBag.AjaxDataTable)",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "Title" },
{ "data": "Firstnames" },
{ "data": "Surname" },
{ "data": "PhoneNumber" }
],
"order": [[1, 'asc']]
});
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
});
function format(d) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Name:</td>' +
'<td>' + d.Surname + '</td>' +
'</tr>' +
'<tr>' +
'<td>Agreement:</td>' +
'<td>' + d.CustomerNumber + '</td>' +
'</tr>' +
'<tr>' +
'<td>System:</td>' +
'<td>' + d.System + '</td>' +
'</tr>' +
'</table>';
}
有人可以告诉我我做错了吗?
非常感谢任何帮助: - )