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

时间:2015-03-11 12:47:36

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我想在一个视图中使用多个模型,我红色的一些文章使用复杂的模型,或部分视图,或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; }
}

2 个答案:

答案 0 :(得分:2)

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

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 )
    .....

并在你的后期行动方法

public ActionResult MethodName(ViewModelName viewModel)
{
    //
}

答案 1 :(得分:1)

尝试创建一个Class(例如Manager),为Department,ClassOut,ClassOutName添加变量,然后将Class Manager传递给视图,然后就可以轻松访问

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