2015-05-06 68 views
-2

Asp.net mvc4 我有兩個數據庫表,例如學生DB和教師分貝,我必須列出單個頁面或單一視圖上都student表和教師表列出兩個表在單個視圖

如何我可以將兩種模型發送到單個視圖嗎?

+2

創建包含學生集合和教師集合屬性的視圖模型 –

+0

請參閱鏈接:http://forums.asp.net/t/1700177.aspx?How+to+Display+Data+in+一個+單個+視圖+從+多重+ +表中+ MVC + 3 + 0 + – Zealous

回答

0

你將有兩個模型,StudentModel,TeacherModel,那麼你必須創建你的視圖模型與這兩個模型,比如說AcadamyViewModel

您的實體將

public class Student 
{ 
    ...............Properties 
    ............... 
} 

public class Teacher 
{ 
    ...............Properties 
    ............... 
} 

你查看模型將

public class AcadamyViewModel 
{ 
    public List<Student> StudentList{get;set;} 
    public List<Teacher> TeacherList{get;set;} 
} 

你的控制器動作將

public ActionResult Index() 
{ 
    var students=dbContext.Students.ToList(); 
    var teachers=dbContext.Teachers.ToList(); 
    var model=new AcadamyViewModel() 
    { 
      StudentList=students, 
      TeacherList=teachers 
    }; 
    return View(model); 
} 

你的看法會

@model MyApp.Models.AcadamyViewModel 

@foreach(var item in Model.StudentList) 
{ 
    ................. 
} 

@foreach(var item in Model.TeacherList) 
{ 
    ............... 
} 

這將工作。

相關問題