In the example below, I am using DI to new up all the Glass Mapper glasses. We are using SitecoreContext and GlasHtml in our repositories to do the work.
Controller
private readonly ICartRepository _cartRepository;
public CartController(ICartRepository cartRepository)
{
_cartRepository = cartRepository;
}
public ActionResult MiniCart()
{
try
{
var model = _cartRepository.GetHeaderMiniCart();
return View(model);
}
catch (Exception e)
{
return IsPageEditorEditing ? ErrorView(e) : View(new MiniCart());
}
}
Repository
private readonly ISitecoreContext _sitecoreContext;
private readonly IGlassHtml _glassHtml;
private readonly IRenderingService _renderingService;
public CartRepository(ISitecoreContext sitecoreContext, IGlassHtml glassHtml, IRenderingService renderingService)
{
_sitecoreContext = sitecoreContext;
_glassHtml = glassHtml;
_renderingService = renderingService;
}
Data function, returns editable HTML so we can edit it as if it were a rendering model.
public MiniCart GetHeaderMiniCart()
{
var model = renderingService.GetGlassModelFromDataSource<Header>();
return new MiniCart
{
Icon = _glassHtml.Editable(model, x => x.CartImage),
Link = _glassHtml.Editable(model, x => x.CartButtonLink),
Count = 2
};
}
The Render Service Helper interface and class.
public interface IRenderingService
{
/// <summary>
/// Get a glass model from the item data source
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>T</returns>
T GetGlassModelFromDataSource<T>() where T : GlassBase;
}
public class RenderingService : IRenderingService
{
/// <summary>
/// Get a glass model from the item data source
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>T</returns>
public T GetGlassModelFromDataSource<T>() where T : GlassBase
{
if (string.IsNullOrEmpty(RenderingContext.Current.Rendering.DataSource))
{
throw new MissingMemberException("A rendering must have a datasource.");
}
return RenderingContext.Current.Rendering.Item.GlassCast<T>();
}
}
The model
public class MiniCart
{
public string Icon {get; set;}
public string Link {get; set;}
public int Count {get; set;}
}
Then in the view
@model MiniCart
My Link @Html.Raw(Model.Link)
My Icon @Html.Raw(Model.Icon)