i have 2 queries in aggregatemodel, , i'd them passed through index view used in 2 separate foreach loop. of moment both being passed through in 1 model.
the model
public class aggregatemodel { public list<task> tasks { get; set; } public list<event> events { get; set; } }
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 majority if view, 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 @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 @html.actionlink("task", "create", "task")</li> </ul> </div>
as can see, foreach loop calls model, has 2 queries in it. have 2 loops each running 1 of queries.
many in advance.
on top of view should have:
@model aggregatemodel
and not
@model ienumerable<task>
then can loop:
@foreach (var item in model.tasks) { } ... @foreach (var item in model.events) { }
and because looping in view ugly should use editor/display templates simplify code to:
@html.displayfor(x => x.tasks) ... @html.displayfor(x => x.events)
where should define corresponding ~/views/shared/displaytemplates/task.cshtml
, ~/views/shared/displaytemplates/event.cshtml
templates rendered each element of collection.
Comments
Post a Comment