GlassView with strongly typed context item and model

I have recently started working with Sitecore MVC using glass mapper. In my project I have several view renderings where I need to access the details of datasource item and as well as current context item. I knew that GlassView class takes the type of model as generic type argument and then if there is data source mentioned for the view rendering then it creates the model from data source item otherwise it creates the model from current context item.

Here my requirement was to use both (model as my data source and current context item) as strongly typed objects in my view renderings. Hence I started to look into the GlassView class and found some interesting public methods and properties that are useful to developers:

Properties:

S.No. Name Purpose
 1. ContextItem Returns the item specified by the current context item.
 2. DataSourceItem Returns the item specificed by the data source only. Returns null if no datasource set.
 3. LayoutItem Returns either the item specified by the DataSource or the current context item.

 

Methods:

S.No. Name Purpose
 1. GetContextItem Returns the Context Item as strongly typed.
 2. GetDataSourceItem Returns the Data Source Item as strongly typed.
 3. GetLayoutItem Returns the Layout Item as strongly typed.
 4. GetRenderingParameters Returns the parameters as strongly typed.

 

As there is out of box support available for strongly types in GlassView for data source and as well as context item so we started with defining a variable in our view renderings as below:

@inherits GlassView<MyDataSource>@{

var pageItem = GetContextItem<MyContentItem>();

}

<div>@pageIem.Title</div>

 

But this was tedious to verify that developers in my team were using this strongly typed approach instead of using the context item directly so I created small abstract class by inheriting from GlassView:

public abstract class CustomGlassView<TModel, TPageItem> : GlassView<TModel>where TModel : classwhere TPageItem : class

{

private TPageItem pageItem;

public TPageItem PageItem

{

get { return pageItem ?? (pageItem = this.GetContextItem<TPageItem>()); }

}

}

 

Now in my view renderings I am able to put the two strongly types for my view class as below:

@inherits CustomGlassView<MyDataSource, MyContentItem><div>@PageItem.Title</div>

This helps a lot in working with view renderings and the same can be done for parameters.

Thanks.

 

Share thisEmail this to someonePrint this pageTweet about this on Twitter0Share on Facebook0Share on Google+0Share on TumblrShare on LinkedIn5
1 vote

2 thoughts on “GlassView with strongly typed context item and model

Leave a Reply

Your email address will not be published. Required fields are marked *


six × = 12

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>