asp.net-mvc - 如何使用 Ado.Net 在 MVC 的 razor 视图中显示外键相关数据
问题描述
这是我的课
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public int DeptId { get; set; }
public Dept Dept { get; set; }
}
为了显示列表,我使用 ado.net。这是我的控制器:
public ActionResult Index()
{
StudentRepo repo = new StudentRepo();
List<Student> students = repo.GetStudent().ToList();
return View(students);
}
GetStudent 方法
public List<Student> GetStudent()
{
connection();
List<Student> stdList = new List<Student>();
SqlCommand com = new SqlCommand("Sp_GetStudent", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
con.Close();
foreach (DataRow dr in dt.Rows)
{
Dept dpt = new Dept();
dpt.DeptId = Convert.ToInt32(dr["DeptId"]);// here found student Id
dpt.Name = Convert.ToString(dr["Name"]);// here found student name
stdList.Add(
new Student
{
StudentId = Convert.ToInt32(dr["StudentId"]),
Name = Convert.ToString(dr["Name"]),
Roll = Convert.ToString(dr["Roll"]),
DeptId = Convert.ToInt32(dr["DeptId"]),
Dept = dpt
}
);
}
return stdList;
}
剃刀观点是:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Roll)
</td>
<td>
@Html.DisplayFor(modelItem => item.Dept.Name)
</td>
</tr>
}
入库流程:
select StudentTbl.StudentId,StudentTbl.Name,StudentTbl.ROll, StudentTbl.DeptId,DeptTbl.Name
from Demo.dbo.StudentTbl inner join
Demo.dbo.DeptTbl ON StudentTbl.DeptId = DeptTbl.DeptId
目前它显示部门ID。现在问题出在列表中,我不知道如何显示部门名称。我怎样才能做到这一点?任何形式的帮助将不胜感激。
编辑:现在当我在 dpt 对象中绑定 Dept 数据时,它会找到 StudentTbl Id & Name
解决方案
通常的解决方案是为您的列名使用别名,以使它们独一无二:
select
StudentTbl.StudentId,
StudentTbl.Name as StudentName,
StudentTbl.ROll,
StudentTbl.DeptId,DeptTbl.Name as DeptName
然后当然更改您的 C# 代码以匹配新别名:
dpt.Name = Convert.ToString(dr["DeptName"]);
和
Name = Convert.ToString(dr["StudentName"])
推荐阅读
- c# - Convert Day count into months and year in C#
- sql - 为变量赋值的 SELECT 语句不能与数据检索操作结合使用;我不认为它是
- mysql - 存储过程中的 if else 有问题
- javascript - v-for 构造中的 Vue JS 模板中的多个临时变量?
- python - 如何修复boto3中不存在用户池********
- laravel - 当我想将 Laravel 项目迁移到我的第二台计算机时,命令提示符中的 Php artisan 迁移会带来错误
- c# - 创建整数定义
- reactjs - React中组件为componentDidMounted时如何获取输入值?
- node.js - 如何从来自 MongoDB 的道具渲染 HTML
- android - DexArchiveBuilderException 与 Firebase 性能监控库,R8 未能脱糖?