我正在做一个项目。我需要从数据库获取一些数据并发送给查看。我已经有了一份数据清单。我还想通过 viewbag 发送我的另一个数据。我从数据库查询了我的相关数据。
类控制器.cs
public ActionResult ClassTeacherDetail(int id)
{
ViewBag.dgr = db.Teachers.Where(m => m.Id == id).FirstOrDefault();
var myList = (from t in db.Appointments
from d in t.WeekDays
where t.TeacherId == id
select new { DayName=d.Name, WHours=t.Hours }
).ToList();
// Get the languages which can be learned by the teacher based on teacher id
var query = from t in db.Teachers.Where(x => x.Id == id)
from l in t.Languages
select new
{
LangName = l.Name,
};
var list = new List<Language>();
foreach (var item in query)
{
list.Add(new Language()
{
Name = item.LangName
});
}
return View(list);
}
如您所见,我从不同的表中获取了工作时间和天数。顺便问一下,myList 的类型是什么?如果我将其发送给查看,模型类型是什么?
如何传递 myList?
myList 是一个
Anonymous object
类型的 List,这没有什么问题,但很难跟踪。我们需要做的是为其创建一个类/模型,然后创建一个包含这两个变量的视图模型。
// if the property/data type doesn't match with your Appointments model, please change accordingly
public class TeacherAppointment {
public string DayName {get;set;}
public string WHours {get;set;}
}
List<TeacherAppointment>
var myList = (from t in db.Appointments
from d in t.WeekDays
where t.TeacherId == id
select new TeacherAppointment { DayName=d.Name, WHours=t.Hours }
).ToList();
public class TeacherDetailViewModel{
public List<TeacherAppointment> TeacherAppointments {get;set;}
public List<Language> Languages {get;set;}
}
@model TeacherDetailViewModel
public ActionResult ClassTeacherDetail(int id)
{
ViewBag.dgr = db.Teachers.Where(m => m.Id == id).FirstOrDefault();
var myList = (from t in db.Appointments
from d in t.WeekDays
where t.TeacherId == id
select new TeacherAppointment { DayName=d.Name, WHours=t.Hours }
).ToList();
// Get the languages which can be learned by the teacher based on teacher id
var query = from t in db.Teachers.Where(x => x.Id == id)
from l in t.Languages
select new
{
LangName = l.Name,
};
var list = new List<Language>();
foreach (var item in query)
{
list.Add(new Language()
{
Name = item.LangName
});
}
// instantiate view model
TeacherDetailViewModel tdvm = new TeacherDetailViewModel();
// assign myList and list to TeacherDetailViewModel
tdvm.TeacherAppointments = myList;
tdvm.Languages = list;
// Pass tdvm to the view
return View(tdvm);
}
@foreach(var a in Model.TeacherAppointments){
...
}
@foreach(var b in Model.Languages){
...
}