MVC 3:将多个查询传递给一个视图 [英] MVC 3: Passing multiple queries to a view

查看:58
本文介绍了MVC 3:将多个查询传递给一个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在AggregateModel中有两个查询,我希望将它们传递给索引视图,以在两个单独的foreach循环中使用.但目前它们都在一个模型中通过.

I have two queries in an AggregateModel, and I'd like them to be passed through to the index view to be used in two separate foreach loop. But as of the moment they are both being passed through in one model.

模型

public class AggregateModel
{
    public List<Task> Tasks { get; set; }
    public List<Event> Events { get; set; }
}

HomeController.cs

HomeController.cs

var model = new AggregateModel();
model.Tasks = db.Task.Where(n => (n.UserId == UserID) && (n.Completed == false) && (n.Due < dateTime)).ToList();
model.Events = db.Events.Where(n => (n.UserId == UserID) && (n.Start < dateTime)).ToList();

return View(model);

如果视图已删除冗余位,则为多数:

This is the majority if the view, with the redundant bits removed:

@model IEnumerable<ProjectApp.Models.AggregateModel>

<div id="upcoming-tasks">
    <h4>Your Upcoming Tasks</h4>

    <ul class="upcoming">
    @foreach (var item in Model.Tasks)
    {
        <li>@Html.ActionLink(item.Title, "Details", new { id = item.TaskId })</li>
    }
    <li>Add a @Html.ActionLink("Task", "Create", "Task")</li>
    </ul>
</div>

<div id="upcoming-events">
    <h4>Your Upcoming Events</h4>

    <ul class="upcoming">
    @foreach (var item in Model.Events)
    {
        <li>@Html.ActionLink(item.Title, "Details", new { id = item.EventId })</li>
    }
    <li>Add a @Html.ActionLink("Task", "Create", "Task")</li>
    </ul>
</div>

如您所见,foreach循环调用Model,其中包含两个查询.我想有两个循环,每个循环运行一个查询.

As you can see, the foreach loop calls Model, which has two queries in it. I would like to have two loops each running one of the queries.

非常感谢.

推荐答案

在视图顶部,您应该具有:

On the top of your view you should have:

@model AggregateModel

而不是

@model IEnumerable<Task>

然后您可以循环:

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

...

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

由于视图循环很丑陋,因此您应使用编辑器/显示模板,以将代码简化为:

and because looping in view is ugly you should use editor/display templates which will simplify your code to:

@Html.DisplayFor(x => x.Tasks)
...
@Html.DisplayFor(x => x.Events)

应在其中定义相应的〜/Views/Shared/DisplayTemplates/Task.cshtml 〜/Views/Shared/DisplayTemplates/Event.cshtml 模板为集合的每个元素呈现.

where you should define the corresponding ~/Views/Shared/DisplayTemplates/Task.cshtml and ~/Views/Shared/DisplayTemplates/Event.cshtml templates which will be rendered for each element of the collection.

这篇关于MVC 3:将多个查询传递给一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆