如何使用ViewModel从多个模型显示值



我需要一个表格中包含来自视图模型的数据,其中包含对两个模型的参考。所以:我有StudentModelClassModel和A StudentClassViewModel

我应该在控制器中做什么并查看以正确显示学生和连接的类模型中的所有属性?请任何东西。

这是我的模型(我首先使用代码(

public class Class
{
    public int ClassId { get; set; }
    public string Name{ get; set; }   
    public ICollection<Student> Student { get; set; }
}
public class Student
{
    public int StudentId { get; set; }
    public string Name{ get; set; } 
    public Class Class { get; set; }
    public int ClassId { get; set; }
}
public class StudentClassViewModel
{
    public Class Class { get; set; }
    public Student Student { get; set; }
}

这就是我的方式。

控制器:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //can be fetched from database or your own custom implementation
            Class myClass = new Class()
            {
                ClassId = 1,
                Name = "Class 1"
            };
            Student myStudent = new Student()
            {
                Class = myClass,
                ClassId = 1,
                Name = "John Doe",
                StudentId = 1
            };
            StudentClassViewModel studentClassViewModel = new StudentClassViewModel()
            {
                Class = myClass,
                Student = myStudent
            };
            return View(studentClassViewModel);
        }

    }

查看:

@model stackoverflow.Models.StudentClassViewModel
@{
    ViewBag.Title = "Home Page";
}
<table>
    <thead>
        <tr><td>Student ID</td><td>Student Name</td><td>Class ID</td><td>Class Name</td></tr>
    </thead>
    <tbody>
        <tr>
            <td>@Model.Student.StudentId</td>
            <td>@Model.Student.Name</td>
            <td>@Model.Student.Class.ClassId</td>
            <td>@Model.Student.Class.Name</td>
        </tr>
        <!--OR-->
        <tr>
            <td>@Model.Student.StudentId</td>
            <td>@Model.Student.Name</td>
            <td>@Model.Class.ClassId</td>
            <td>@Model.Class.Name</td>
        </tr>
    </tbody>
</table>

相关内容

  • 没有找到相关文章