我有两个模型,我需要在布局页面和用户访问的每个页面中显示数据。这两个模型之间没有任何关系,所以我不需要任何连接。
这是我的控制器
public ActionResult Index()
{
var notification = (from n in db.Notification
where n.NotificationIsSeen == true
select n);
var task = (from t in db.Task
where t.TaskIsSeen == true
select t);
return View();// I not sure how to return both of queries
}
我还创建了一个包含这两个的模型,但我不确定这是否是的正确方式
public class Layout
{
public Notification Notification { get; set; }
public Task Task { get; set; }
}
在我的布局页面
@model IEnumerable<MyprojectName.Models.Layout>
//other code
@foreach (var item in Model)
{
<li>@Html.DisplayFor(modelItem => item.Notification.NotificationSubject ) </li>}
//other code
@foreach (var item in Model)
{
<li>@Html.DisplayFor(modelItem => item.Task.TaskSubject )
</li>
}
我看到过其他类似的问题,但它们适用于联接表。我需要一些关于返回两个表的数据的帮助。提前感谢
操作方法中的查询都返回数据集合。为了适应这种情况,视图模型需要有两个列表,并且需要看起来像这样。当将这些集合发送到视图时,您必须能够将其存储在列表中:
public class Layout
{
public IEnumerable<Notification> Notifications { get; set; }
public IEnumerable<Task> Tasks { get; set; }
}
要填充这些列表,请将操作方法中的代码更改为。创建Layout
的实例,填充两个列表,然后将实例发送到视图:
public ActionResult Index()
{
Layout model = new Layout();
model.Notifications = (from n in db.Notification
where n.NotificationIsSeen == true
select n);
model.Tasks = (from t in db.Task
where t.TaskIsSeen == true
select t);
return View(model);
}
您的观点需要接受Layout
:的实例
@model MyprojectName.Models.Layout
@foreach (var notification in Model.Notifications)
{
<div>
@notification.NotificationSubject
</div>
}
@foreach (var task in Model.Tasks)
{
<div>
@task.TaskSubject
</div>
}
我希望这能有所帮助。
请在布局模型中声明模型的列表类型
布局模型
public class Layout
{
public IEnumerable<Notification> Notifications { get; set; }
public IEnumerable<Task> Tasks { get; set; }
}
控制器
public ActionResult Index()
{
Layout model = new Layout();
model.Notifications = (from n in db.Notification
where n.NotificationIsSeen == true
select n);
model.Tasks = (from t in db.Task
where t.TaskIsSeen == true
select t);
return View(model);
}
查看
@model MyprojectName.Models.Layout
@foreach(var item in Model.Notifications)
{
// access your item.propertyname
}
@foreach(var item in Model.Task)
{
// access your item.propertyname
}
使用局部视图构建动态标头
1-创建具有部分视图和显示数据的动作
2-转到布局以调用此
@Html.partial("Action","Controller")