user704119
user704119

Reputation:

MVC 3: Aggregate model problem

In my HomeController I have the following 3 queries, notice that the 3rd one is not a "ToList", but just the first result being used.

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)).OrderBy(p => p.Start).ToList();
model.NextEvent = db.Events.Where(n => (n.UserId == UserID) && (n.Start < dateTime)).OrderBy(p => p.Start).First();

And in the Model file I have the following model:

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

I need to change the "NextEvent" definition in the model file from "public List" to a different type, but I am not sure of the correct term needed.

Many thanks for any help.

[EDIT]

Basically from the NextEvent model, I want to pull the one result and display it in my view, but the following has a red line under the foreach.

@foreach (var item in Model.NextEvent)
{
    <li>@Html.ActionLink(item.Title, "Details", new { id = item.EventId })</li>
}
</ul>

Upvotes: 0

Views: 751

Answers (2)

Damb
Damb

Reputation: 14600

You are probably looking for

public Event NextEvent {get;set;}

Edit: Ad. second 'foreach' question. Foreach is used only to iterate collections, but NextEvent is a single entity. So there is nothing to iterate with foreach. You can access your NextEvent like this:

<li>@Html.ActionLink(Model.NextEvent.Title, "Details", new { id = Model.NextEvent.EventId })</li>

At least that should work if you didn't rename default model in view.

Model = AggregateModel
Model.NextEvent = AggregateModel.NextEvent

Upvotes: 4

neeebzz
neeebzz

Reputation: 11538

remove the foreach, change the code to >

<li>@Html.ActionLink(Model.NextEvent.Title, "Details", new { id = Model.NextEvent.EventId</li>

Upvotes: 1

Related Questions