这是我的班级
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&amp;姓名
答案 0 :(得分:0)
通常的解决方案是为列名使用别名,使其唯一:
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"])