首页 > 解决方案 > 如何使用 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

标签: asp.net-mvcrazorado.net

解决方案


通常的解决方案是为您的列名使用别名,以使它们独一无二:

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"])

推荐阅读