传统上,我一直在学校通过每页的脚手架制作CRUD表,并想尝试一下是否可以在不使用Partial View的情况下进行所有操作。我选择使用AJAX,并遵循以下指南:https://dzone.com/articles/crud-operation-in-aspnet-mvc-using-ajax-and-bootst
一切正常,但是我想使用DataTable API向表添加搜索和排序功能。这是桌子的样子 HERE。
如您所见,它无法识别来自我制作的JS的数据,最显着的是“显示0项中的0到0”。有什么方法可以将数据从AJAX加载到DataTable脚本吗?非常感谢!我将在下面提供我的代码。
编辑:我将DataTable初始化放在Inventory.js中,并且DataTable SOMETIMES在页面加载时起作用。尝试多次刷新页面时,这是非常随机的。我尝试在页面加载之前放置一个延迟,以查看是否有任何区别,但这不起作用。有人知道会发生什么吗?
库存(模型)
public List<Inventory> ListAll()
{
List<Inventory> lst = new List<Inventory>();
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = @"SELECT * FROM Inventory";
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
lst.Add(new Inventory
{
InventoryId = Convert.ToInt32(dr["inv_id"]),
Category = Helper.Decrypt(dr["category_name"].ToString()),
Name = Helper.Decrypt(dr["item_name"].ToString()),
Details = Helper.Decrypt(dr["item_details"].ToString()),
Quantity = Convert.ToInt32(dr["quantity"]),
CsbCode = Helper.Decrypt(dr["csb_code"].ToString()),
Notes = Helper.Decrypt(dr["notes"].ToString()),
Location = Helper.Decrypt(dr["location"].ToString()),
DateCreated = DateTime.Parse(dr["date_created"].ToString()),
LastModified = DateTime.Parse(dr["last_modified"].ToString()),
});
}
return lst;
}
}
}
}
InventoryController.cs
public JsonResult List()
{
return Json(invDB.ListAll(), JsonRequestBehavior.AllowGet);
}
Inventory.js(如何获取数据)
function loadData() {
$.ajax({
url: "/Inventory/List",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.InventoryId + '</td>';
html += '<td>' + item.Category + '</td>';
html += '<td>' + item.Name + '</td>';
html += '<td>' + item.Details + '</td>';
html += '<td>' + item.Quantity + '</td>';
html += '<td>' + item.CsbCode + '</td>';
html += '<td>' + item.Notes + '</td>';
html += '<td>' + item.Location + '</td>';
html += '<td>' + dateTimeFormat(item.DateCreated) + '</td>';
html += '<td>' + dateTimeFormat(item.LastModified) + '</td>';
html += '<td><a href="#" onclick="return getbyID(' + item.InventoryId + ')">Edit</a> | <a href="#" onclick="Delele(' + item.InventoryId + ')">Delete</a></td>';
html += '</tr>';
});
$('.tbody').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
索引(DataTable脚本):
@section scripts {
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.uikit.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>
<script>
$(document).ready(function () {
$('#user').DataTable({
dom: 'Bfrtip',
buttons: [
'print'
]
});
});
</script>
}
答案 0 :(得分:0)
我正在使用1.10 jQuery数据表,而对于模板,我正在使用Underscore JS。
这是我从服务器端加载的代码。
将此模板和表格放入html代码中。
<table class="table table-bordered table-condensed" id="tblAccounts"></table>
<script type="text/template" id="tmpl_Grid">
<td><%= Id %></td>
<td><%= Amount %></td>
<td><%= Date %></td>
<td><%= Type %></td>
</script>
然后使用此方法让js从服务器端加载数据。
function Load() {
var tmpl = _.template($('#tmpl_Grid').html());
$('#tblAccounts').DataTable({
"dom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
"paging": true,
"info": true,
"ordering": true,
"search": true,
"processing": true,
"serverSide": true,
"destroy": true,
"ajax": {
"url": "/Accounts/LoadList",
"type": "POST",
"data": function (d) {
d.startDate = $("#txtStartDate").val();
d.endDate = $("#txtEndDate").val();
}
},
"columns": [
{ "data": null, "title": "ID", "className": "", "orderable": false, "searchable": false },
{ "data": null, "title": "AMOUNT", "className": "", "orderable": false, "searchable": false },
{ "data": null, "title": "DATE", "className": "", "orderable": false, "searchable": false },
{ "data": null, "title": "TYPE", "className": "", "orderable": false, "searchable": false }
],
"order": [[0, "asc"]],
"rowCallback": function (row, data) {
$(row).html(tmpl(data));
},
"initComplete": function (settings, json) {
}
});
}
这是控制器的代码。我正在使用EntityFrameword进行数据库处理,您可以使用自己的方法或技术。
[HttpPost]
public async Task<JsonResult> LoadList(string startDate, string endDate)
{
var search = Request.Form["search[value]"] + "";
var totalCount = 0;
var fList = _context.Expenses.Include(x => x.AccountType).AsQueryable();
if (!string.IsNullOrEmpty(search))
{
fList = fList.Where(x => x.Description.ToLower().Trim().Contains(search.ToLower().Trim()));
}
var list = await fList.OrderByDescending(x => x.Id).Skip(start).Take(length).Select(x => new
{
x.Id,
x.Amount,
Date = x.Date != null ? x.Date.Value.ToString("dd-MMM-yyyy") : "",
Type = x.AccountTypeId != null ? x.AccountType.Name : "",
x.Description,
x.BillAmount,
x.Payment,
x.AccountTypeId
}).ToListAsync();
if (list.Any())
{
totalCount = fList.Count();
}
var result = JObject.FromObject(new
{
draw,
recordsFiltered = totalCount,
recordsTotal = totalCount,
data = list
});
return result;
}
答案 1 :(得分:0)
感谢您的帮助。我可以使它与在同一论坛上找到的帖子保持一致。
我更改了获取数据的代码。显然,您需要附加数据,这是使我的DataTables正常工作的最重要的事情。
$(“#user tbody”)。append(html);
$.ajax({
url: "/Artwork/List",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
$.each(result, function (key, item) {
var html = '';
html += '<tr>';
html += '<td>' + item.ArtID + '</td>';
html += '<td>' + item.Name + '</td>';
html += '<td>' + item.Details + '</td>';
html += '<td>' + item.Location + '</td>';
html += '<td>' + item.Notes + '</td>';
html += '<td>' + dateTimeFormat(item.DateCreated) + '</td>';
html += '<td>' + dateTimeFormat(item.LastModified) + '</td>';
html += '<td><a href="#" onclick="return getbyID(' + item.ArtID + ')">Edit</a> | <a href="#" onclick="Delele(' + item.ArtID + ')">Delete</a></td>';
html += '</tr>';
$("#user tbody").append(html);
});
$('#user').DataTable({
destroy: true,
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
exportOptions: {
columns: ':visible' ,
}
},
'colvis'
],
columnDefs: [{
visible: false
}]
});
再次,谢谢!