I'm in the midst of setting up an Umbraco 8 website and have run into some weird behaviour. The project is using .NET 4.7.2.
Basically, I have an IENumerable of type Event
, a simple list of content that I'd like to render in to a list. However, whenever I do anything with the list (which has items), the list is immediately emptied. This includes simply assigning to a different variable, checking for null etc.
I don't believe this is an Umbraco 8 issue but for clarity, I'm currently running through a Surface Controller and render it by calling the following in my view:
@Html.Action("RenderUpcoming", "Events")
This is the controller:
using Index.Models.Events;
using Index.Models.PublishedContent;
using Papermoon.Umbraco.Kupo.Core.Services.Interfaces;
using System;
using System.Linq;
using System.Web.Mvc;
using Umbraco.Web.Mvc;
namespace Index.Web.Controllers.Surface
{
public class EventsController : SurfaceController
{
private readonly KupoGeneralSettings _kupoGeneralSettings;
public EventsController(IKupoSettingsService kupoSettingsService)
{
_kupoGeneralSettings = kupoSettingsService.GetSettings<KupoGeneralSettings>("kupoGeneralSettings");
}
public ActionResult RenderUpcoming()
{
UpcomingEventsModel model = new UpcomingEventsModel();
model.Title = "Upcoming Events";
model.Events = Umbraco.ContentAtXPath("root/homepage/events/event").Select(x => new Event(x));
model.Events = model.Events.Where(x => x.StartDate > DateTime.Now).OrderBy(x => x.StartDate).Take(3);
model.TotalEvents = model.Events.Count();
model.EventListingLink = _kupoGeneralSettings.EventListingLink;
return PartialView("~/Views/Partials/Events/UpcomingEvents.cshtml", model);
}
}
}
So here, when I call model.Events = model.Events.Where(x => x.StartDate > DateTime.Now).OrderBy(x => x.StartDate).Take(3);
- I have results then when I do model.TotalEvents = model.Events.Count();
the list (model.Events) is then empty.
This also happens when I assign to another variable, when I call model.Events.Any()
, or when I even do Model.Events != null
.
It's potentially easier to show this than tell so see the accompanying gif of this happening: https://i.sstatic.net/cEC77.gif
Thanks,
Ben
Sure – you don't know the actual type of the object other than that it's something you can iterate over (an IEnumerable
).
It could be a generator that returns an infinite stream of things, for instance (well, in this case you know it's not).
If you need a concrete collection, you could use .ToList()
to cast it into a List<>
you can certainly iterate over multiple times.