我有下表:
| Math | English | Chemistry
John J. | A | F | B
Mike M. | A | F | B
Eve E. | A | F | B
所以我有可变数量的列(可以在运行时设置)和可变数量的学生。
我的 SQL 数据库可以看起来像:
Table 1
studentID
studentName
studentAddress
Table 2:
disciplineID
disciplineName
disciplineTeacher
Table 3:
studentID
disciplineID
grade
我的模型应该是什么样子的?我可以做类似的事情吗:
public class Catalog
{
public int ID { get; set; }
public virtual IEnumerable<Discipline> Disciplines { get; set; }
public virtual IEnumerable<Student> Students { get; set; }
public virtual IEnumerable<Grades> StudentGrades { get; set; }
}
internal class Discipline
{
public int ID { get; set; }
public string Name { get; set; }
}
internal class Student
{
public int ID { get; set; }
public string Name { get; set; }
}
internal class Grades
{
public int StudentId { get; set; }
public int DisciplineId { get; set; }
public char Grade { get; set; }
}
这是执行此多列/运行时定义的常规方法吗? 我如何确保规程在 View 中始终处于相同的顺序? 我如何确保在 View 中呈现表格行时,为每个学生显示正确学科的正确成绩?
谢谢!
最佳答案
Is this the normal way to do this multi-column/run-time definition?
这不是唯一的方法,但(对我而言)将所有单独的数据传递给 View 并让 View 对其进行排序似乎没有任何问题。
您可以将学生转换为 ILookup - 这将减少 View 中的代码。
How can I ensure the disciplines are always in the same order in the view?
到目前为止,您还没有包含您尝试过的内容。
本质上:循环遍历每个学生,然后循环遍历每个学科并找到每个学科对应的成绩 - 如果没有,则显示“-”
类似于:你应该使用@Html.DisplayFor 等
<tbody>
@foreach(var student in Model.Students)
{
<tr>
<td>@student.Name</td>
@foreach(var discipline in Model.Disiplines)
{
var grade = Model.Grades.Where(
x => x.StudentId == student.StudentId
&& x.DisciplineId == discipline.DisciplineId)
.FirstOrDefault();
<td>
@(grade==null ? "-" : grade.Grade)
</td>
}
</tr>
}
关于mysql - 在 MVC 中创建可变列表模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30322604/