I have 10 content spots. I would like a page to show 1 of them randomly.
I have tried using the Function 'ShowContentSpots' - but that shows all of them & doesn't cycle through.
What's the best way of doing this?
You should edit the ShowContentSpots function and:
A quick solution would be:
@if (!string.IsNullOrEmpty(ContentSpotIds))
{
var rand = new Random();
var spotIds = ContentSpotIds.Split(',').Select(f=>new Guid(f));
var spots = Data.Get<Content.ContentSpot>().Where(f=> spotIds.Contains(f.Id)).ToList();
if (spots.Any())
{
var spot = spots[rand.Next(spots.Count)];
<div class="spots">
<div class="spot">
@Html.Raw(spot.Content)
</div>
</div>
}
}
Please note that this is part of the original function's code. Here I added:
var rand = new Random();
and modified this part:
var spot = spots[rand.Next(spots.Count)];
<div class="spots">
<div class="spot">
@Html.Raw(spot.Content)
</div>
</div>
This is just a quick sample. So when you refresh the page very quickly the spot might not change every time - because we create a new Random object every time we refersh the page.
To avoid this, initialize the Random object only once and somewhere else, and use it in this function.