ASP.MET 一个视图中的 MVC 多模型

ASP.MET MVC Multiple Model in One View

我想在一个视图中使用多个模型,我红了一些文章使用复杂模型,或分部视图,或Viewbag等,但找不到正常答案。

我想显示来自不同模型的数据。 这是我的模型

 public class Department
{
    public int DepartmentID { get; set; }
    public string DepartmentName { get; set; }
    public string Image { get; set; }

    public IEnumerable<Teacher> Teachers { get; set; }
}

 public class Teacher
{
    public int TeacherID { get; set; }
    public string TeacherName { get; set; }
    public string TeacherLname { get; set; }
    public int DepartmentID { get; set; }
    public string Image { get; set; }

    public Department Department { get; set; }


}
 public class ClassOut
{
    public int Id { get; set; }
    public string ClassOutName { get; set; }
}



 public class SchoolDbContext:DbContext
{
    public DbSet<Teacher> Teachers { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<ClassOut> ClassOuts { get; set; }
}

尝试创建一个 Class(例如经理),在其中为 Department、ClassOut、ClassOutName 添加一个变量,然后传递 Class经理到视图然后你就可以轻松访问

public class Manager
{
  public Department dept;
  public ClassOut cl;
  public ClassOutName clname;
}

将所有模型合并到一个通用视图模型中,并在您的视图中使用它。

public class ViewModelName 
{
    public Department Department {get; set;}
    public Teacher Teacher {get; set;}
    public ClassOut ClassOut {get; set;}
}

将此模型用于您的视图:

    @model ViewModelName
    ......
    @Html.TextBoxFor(x => x.Teacher.TeacherName )
    .....

并且在您的 post 操作方法中

public ActionResult MethodName(ViewModelName viewModel)
{
    //
}