asp.net-core - 如何显示来自另一个表的列数据而不是数据表的外键数据
问题描述
我正在 ASP.NET Core 3.1 中实现一个解决方案。我有一个 DataTable,我想通过 ajax 调用将数据加载到其中,如下所示,它将数据完全加载到其中:
jQuery(document).ready(function ($) {
$("#myDummyTable").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false,
"ajax": {
"url": "MyData/GetData",
"type": "POST",
"datatype": "jason"
},
"columnDefs": [{
"targets": [0],
"visible": false,
"searchable": false
}],
"columns": [
{ "data": "id", "name": "Id", "autoWidth": true },
{ "data": "name", "name": "Name", "autoWidth": true },
{ "data": "applicantId", "name": "applicantId", "autoWidth": true },
]
});
});
但我的问题是applicantId
在上面的列中是另一个表的外键调用Applicant
,而不是applicantId
值本身是一个数字,我想在 jQuery Datatable 视图中显示Name
相关列的数据。Applicant
如果有人能建议如何做到这一点,我将不胜感激。
解决方案
看来您想显示嵌套模型列,您可以查看下面的演示:
模型:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
public int ApplicantId { get; set; }
public Applicant Applicant { get; set; }
}
public class Applicant
{
public int Id { get; set; }
public string Name { get; set; }
public List<Test> Tests { get; set; }
}
看法:
<table id="myDummyTable" class="display" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>applicantname</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>goodsName</th>
<th>applicantname</th>
</tr>
</tfoot>
</table>
在视图中的 JS:
@section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
jQuery(document).ready(function ($) {
$("#myDummyTable").DataTable({
"ajax": {
"url": "/MyData/GetData", //be sure the request url is correct,it should be `/xxx/xxx` not `xxx/xxx`
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "id", "name": "Id", "autoWidth": true },
{ "data": "name", "name": "Name", "autoWidth": true },
//change here...
{ "data": "applicant.name", "name": "applicant.name", "autoWidth": true },
]
});
});
</script>
}
控制器:
[HttpPost]
[Route("MyData/GetData")]
public IActionResult TestData()
{
var data = new List<Test>()
{
new Test(){Id=1,Name="aa",Applicant=new Applicant(){ Id=1,Name="app1"} },
new Test(){Id=2,Name="bb",Applicant=new Applicant(){ Id=1,Name="app2"} },
new Test(){Id=3,Name="bb",Applicant=new Applicant(){ Id=1,Name="app3"} }
};
return Json(new { data = data });
}
推荐阅读
- mysql - 在基于外键检索多条记录时,有没有办法优化查询?
- android - GridLayoutManager 垂直填充项目
- python - MySQL - 用 Python 替换列的所有字符
- android - 后台服务中麦克风和扬声器中使用的自动语音监听器
- javascript - flatpickr 配置 - 如何为新记录设置今天的默认日期,但在更新现有记录时保留存储的值
- java - 观察变量的变化
- python - 在本地文件夹中从 github 安装 python 包/模块并使用它
- c# - 如何修复 System.IO.FileNotFoundException
- java - org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“userController”的bean时出错:
- sql - 如何在没有where子句的表中选择第二行