0

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?

niico
  • 11,206
  • 23
  • 78
  • 161

1 Answers1

1

You should edit the ShowContentSpots function and:

  1. change the code so that only one item is retrieved (not all)
  2. add some randomizer when retrieving a single item

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.

wysocki
  • 731
  • 5
  • 7
  • Thanks. I am editing through the CMS only. How do I get to that function? – niico Sep 25 '13 at 10:40
  • Functions perspective / Razor Functions / Content / ShowContentSpots. Maybe a good approach would be to create another Razor Function based on this one (you can select which function to base on when creating) and experiment with this copied function :) – wysocki Sep 25 '13 at 12:05