MVC在单击按钮时从JSon对象填充JQuery数据表时出现问题
我有一个MVC页面,其中有一个JQuery数据表,我希望在用户单击Query按钮时填充该表 这是我的数据表:MVC在单击按钮时从JSon对象填充JQuery数据表时出现问题,jquery,json,asp.net-mvc,datatables,Jquery,Json,Asp.net Mvc,Datatables,我有一个MVC页面,其中有一个JQuery数据表,我希望在用户单击Query按钮时填充该表 这是我的数据表: <table id="mytable" class="table table-striped table-bordered mt-5"> <thead> <tr> <th>Column 1</th> <th>Column 2</th> <th&
<table id="mytable" class="table table-striped table-bordered mt-5">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
<th>Column 6</th>
<th>Column 7</th>
</tr>
</thead>
<tbody></tbody>
</table>
下面是当用户单击查询按钮时调用的函数:
$('#mytable').DataTable({
processing: true, // for show progress bar
order: [[2, "desc"]],
dataSrc: 'vm',
dom: 'rfltip',
bRetrieve: true,
iDisplayLength: 50,
columns: [
{ "data": "COL1" },
{ "data": "COL2" },
{ "data": "COL3" },
{ "data": "COL4" },
{ "data": "COL5" },
{ "data": "COL6" },
{ "data": "COL7" }
]
});
function QueryEvents() {
$.ajax({
url: "/MyController/MyJsonRequest",
type: "get",
data: {
id: $("#id").val()
},
error: function (response) {
console.log("response: " + response);
}
})
.done(function (result) {
var table = $('#mytable').DataTable();
table.clear().draw();
console.log('good to here' + JSON.stringify(result));
table.rows.add(result).draw();
});
};
对控制器的调用正在运行并返回一个Json对象。下面是console.log条目中的对象列表,因此我知道正在返回数据:
good to here{"vm":[{"COL1":"0000000017","COL2":"Balance - 4 Place","COL3":"2334234","COL4":"INS1234","COL5":"smith, joe","COL6":"Yearly Maint","COL7":"/Date(1582314988910)/"},{"COL1":"0000000018","COL2":"Balance - 4 Place","COL3":"2334234","COL4":"INS1234","COL5":"jones, billy","COL6":"Yearly Maint","COL7":"/Date(1582314988910)/"}]}
它是格式良好的json,我没有收到任何错误,但是数据表没有填充。不确定我遗漏了什么?以下是您在控制台上打印的对象
{"vm":[{"COL1":"0000000017","COL2":"Balance - 4 Place","COL3":"2334234","COL4":"INS1234","COL5":"smith, joe","COL6":"Yearly Maint","COL7":"/Date(1582314988910)/"},{"COL1":"0000000018","COL2":"Balance - 4 Place","COL3":"2334234","COL4":"INS1234","COL5":"jones, billy","COL6":"Yearly Maint","COL7":"/Date(1582314988910)/"}]}
但DataTable只需要内部数组
[{"COL1":"0000000017","COL2":"Balance - 4 Place","COL3":"2334234","COL4":"INS1234","COL5":"smith, joe","COL6":"Yearly Maint","COL7":"/Date(1582314988910)/"},{"COL1":"0000000018","COL2":"Balance - 4 Place","COL3":"2334234","COL4":"INS1234","COL5":"jones, billy","COL6":"Yearly Maint","COL7":"/Date(1582314988910)/"}]
所以你应该使用
table.rows.add(result.vm).draw();
而不是
table.rows.add(result).draw();