c# - 我的控制器返回正确的数据,但数据表没有对其进行可视化
问题描述
我第一次使用Datatables时遇到了一个很奇怪的问题。我的操作将带有正确数据的 JSON 响应返回到数据表,但在视图中我没有收到带有填充数据的表格,而是 JSON 格式的数据。问题出在哪里?
public class Proba
{
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
行动是
public ActionResult UserList()
{
var data = context.Probas.ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
看法
@model IEnumerable<MSklad.Models.Proba>
<div class="col-md-12" style="margin-top: 30px;">
<input type="button" class="btn btn-info" value="Нов потребител" onclick="location.href='@Url.Action("Register", "Account")'" style="margin-bottom: 10px;"/>
<table id="myTable">
<thead>
<tr>
<th>
Id
</th>
<th>
Name
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
@section Scripts
{
<script>
$(document).ready( function () {
$('#myTable').DataTable(
{
"responsive": "true",
"ajax": {
"type" : "GET" ,
"url" : "@Url.Action("UserList","Account")" ,
"datatype" : "json"
},
"columns":
[
{ "data": "Id" },
{ "data": "Name"}
],
"language": {
"processing": "<img src='https://gph.is/2gESFHh' />",
"emptytable": "No data found, You may click on <b> Add New </b> button"
}
});
});
</script>
}
浏览器中的响应
{"data":[{"Id":"1","Name":"ime","Age":1}]}
解决方案
您的 JSON 有一个数据属性 {"data":[{"Id":"1","Name":"ime","Age":1}]}。只需添加“dataSrc”:“data”
$(document).ready(function () {
$('#myTable').DataTable(
{
"responsive": "true",
"ajax": {
"type": "GET",
"url": "@Url.Action("UserList","Account")" ,
"datatype": "json",
"dataSrc": "data"
},
"columns":
[
{ "data": "Id" },
{ "data": "Name" }
],
"language": {
"processing": "<img src='https://gph.is/2gESFHh' />",
"emptytable": "No data found, You may click on <b> Add New </b> button"
}
});
});
在您的帐户控制器中,创建一个操作方法,我命名我的索引,它将带我到带有 DataTables 的视图
public ActionResult Index()
{
return View();
}
然后从您的视图中使用 DataTable 中的 ajax,您将调用另一个操作方法
public JsonResult UserList()
{
var data = context.Probas.ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
您将有两种 Action 方法,一种将带您到您的视图,另一种将在从 DataTable 调用时返回 Json 数据
推荐阅读
- c - 如何在不使用强制转换的情况下 printf _ExtInt?
- java - 二进制搜索适用于整数数组,但不适用于双精度数组
- android - 就性能而言,一个约束布局还是三个线性布局哪个更好?
- java - 数组值大于右边?
- r - 为什么一个类别变量的一个级别的自由度与 lme 中的其他级别不同?
- mysql - 如何编写像这个表结构这样的查询?
- powershell - Powershell 脚本停止 .mp3
- dart - Dart - 如何在抽象类中调用泛型类型的方法
- haskell - Haskell 类型类可以部分实现吗?
- json - ESP32 连接到 Weather API 以使用 JSON 数组获取信息