Controller Rendering based on Media Library source - Hero Slider
- Controller
- View
Controller (HeroSliderController.cs)
using Sitecore;
using Sitecore.Data.Items;
using Sitecore.Mvc.Presentation;
using System;
using System.Web.Mvc;
namespace Solution.Controllers
{
// Controller
public class HeroSliderController : Controller
{
// Controller Action
public ViewResult Hero()
{
Item contentItem = null;
var database = Context.Database;
if (database != null)
{
if (!String.IsNullOrEmpty(
RenderingContext.Current.Rendering.DataSource))
{
contentItem = database.GetItem(new Sitecore.Data.ID(
RenderingContext.Current.Rendering.DataSource));
}
}
return View(contentItem);
}
}
}
View (HeroSlider.cshtml)
@model Sitecore.Data.Items.Item
@using Sitecore.Data.Fields
@using Sitecore.Data.Items
@using Sitecore.Resources.Media
@{
Layout = null;
}
@if (Model != null)
{
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
@{
IEnumerable<Item> heroImages = null;
var heroImagesField = new MultilistField(
Model.Fields["Hero Images"]);
if (heroImagesField != null)
{
heroImages = heroImagesField.GetItems();
}
if (heroImages != null)
{
int i = 1;
foreach (var image in heroImages)
{
var mediaItem = (MediaItem)image;
<div class="item @(i == 1 ? "active" : "")">
<img src="@MediaManager.GetMediaUrl(mediaItem)" style="width:1920px;" alt="@mediaItem.Alt" />
</div>
i++;
}
}
}
</div>
</div>
}
In order for this to work, you need to create a template in Sitecore with Field name Hero Images, Type of Treelist, and Source of where you are storing your images.
Name | Type | Source |
---|---|---|
Hero Images | Treelist | /sitecore/media library/Hero Images |
When you create an item based on this template you will see something similar to the screenshot below:
This will be your source where you will feed items into your Hero Slider.
Create Hero Slider Component in Sitecore
Next step will be to create a Hero Slider Component that will render on the page.
Inside /sitecore/Layout/Renderings create a Controller Rendering and add the following information:
Controller | Controller Action |
---|---|
HeroSlider | Hero |
It should look similar to the screenshot below, depending on your configurations it will be different.
Last part, you just need to add it to the page inside of the placeholder and specify the datasource.