创建一个 StudentCoachViewModel,其中包含您需要显示的属性,仅此而已。
在控制器中填充此视图模型的列表并将其发送到您的视图。稍后将提供代码示例。
枚举您视图中的该列表
public class StudentCoachViewModel
{
public string CoachName { get; set; }
public string StudentName { get;set; }
}
在你的控制器中,有以下几行内容(只是输入此内容,尚未在编译器中检查)
public ActionResult Index()
{
//code to populate your model1 and model2 already assumed
var viewModels = (from m in model1List
join r in model2List on m.CoachId equals r.CoachId
select new StudentCoachViewModel(){ StudentName=m.StudentName,
CoachName = r.CoachName }).ToList();
return View(viewModels);
}
在您看来,类似的东西(显然您想要格式化并使用正确的布局、表格等,这些可以由 Visual Studio 自动生成)
@model IEnumerable<StudentCoachViewModel>
//other html content here
@foreach(var viewModel in Model)
{
@Html.DisplayFor(o=>o.CoachName) @Html.DisplayFor(o=>o.StudentName)
}
现在,如果您只想要一个而不是列表,那就更容易了
public ActionResult Index(int id)
{
//code to load model1 and model2 already assumed to be in place. also assuming you loaded this data from a database by the id field being passed into this method.
return View(new StudentCoachViewModel(){ StudentName = model1.StudentName, CoachName = model2.CoachName});
}
然后视图就变得简单了
@model StudentCoachViewModel
//other html here, h1, divs, etc whatever is in your view as html content.
@Html.EditorForModel()
or if you like to display each one instead of the above one line call:
@Html.LabelFor(o=>o.CoachName)
@Html.EditorFor(o=>o.CoachName)