如何在mvc4 razor的View中显示数据库中两个表的数据

时间:2015-11-26 08:01:20

标签: sql-server asp.net-mvc-4 razor

任何人都可以指导我如何使用razor在MVC4的视图页面中显示数据库中两个表的数据吗?我搜索了它但我没有找到答案

LeadDetail.cs

 public partial class LeadDetail
 {
    public int LeadID { get; set; }
    public string LeadName { get; set; }

    public virtual logintable logintable { get; set; }
 }

EmployeDetail.cs

 public partial class EmployeDetail
 {
    public int EmployeID { get; set; }
    public int UserID { get; set; }
    public string EmployeeName { get; set; }


    public virtual logintable logintable { get; set; }
  }

viewmodels文件夹中的Parentview.cs

 public class Parentview
 {
    public List<LeadDetail> LeadDetails { get; set; }
    public List<EmployeDetail> EmployeDetails { get; set; }

    public ParentsInformationViewModel(List<LeadDetail> _LeadDetails, List<EmployeDetail> _EmployeDetails) //Should i pass all the required parameters that i want to display in view ????
    {
        LeadDetails = _LeadDetails;
        EmployeDetails = _EmployeDetails;

    }

Homecontroller.cs

 public ActionResult view()
    {
        List<LeadDetail> LeadObj = new List<LeadDetail> ();
        List<EmployeDetail> EmployeObj = new List<EmployeDetail> ();
        // get list of parents here

        Parentview   ParentInfoVMObj = new Parentview();
        ParentInfoVMObj.LeadDetails = LeadObj;
        ParentInfoVMObj.EmployeDetails = EmployeObj;


        return View(ParentInfoVMObj);
    }

2 个答案:

答案 0 :(得分:0)

见下面的样本

第一张表

public class Table1
    {
        public int Id{ get; set; }
        public string Name{ get; set; }
    }

第二张表

public class Table2
    {
        public int Id{ get; set; }
        public string Name{ get; set; }
    }

<强>视图模型

public class ViewModelForTwoTables
    {
        public List<Table1> table1Data { get; set; }

        public List<Table2> table2Data { get; set; }
    }

答案 1 :(得分:0)

见下面的例子

public ActionResult TeamStat()
{
 var players = db.Players().ToList();
 var seasons = db.Seasons().ToList();
var view = new TeamStat()
{
Players = players,
Seasons = seasons
};
return View(view);
}

在视图中

@foreach (var player in Model.Players) { .... 
@foreach (var player in Model.Seasons) { ....