0

I am using glass mapper and have a Controller Rendering with a DataSource specified. In the controller I am using the following code

        var context = new SitecoreContext();


        var siteSettings = context.GetItem<Alert_Settings>(RenderingContext.Current.Rendering.Item.ID.Guid);
        return View(siteSettings);

However siteSettings return null. Plus what is the difference between

RenderingContext.Current.Rendering.Item 

and

RenderingContext.Current.Rendering.DataSource

I noticed that .DataSource returns only the guid(string) where as the Rendering.Item returns the complete datasource item.

1

You need to do the following to get the item back:

var siteSettings = this.GetDataSourceItem<Alert_Settings>();
return View(siteSettings);

But you must inherit from the GlassController to have access to the GetDataSourceItem method. This will return your strongly typed model instead of the guid for your datasource item. If you don't have the ability to inherit in your current Controller directly from GlassController, you can use a different base controller (which we typically do in our own instances) and have that controller reference the GlassController.

However if you still need to do it without access to the GetDataSourceItem method on the Glass Controller, you could do the following instead:

Guid dataSourceId = RenderingContext.Current.Rendering.DataSource;

if (dataSourceId != Guid.Empty) {
    var siteSettings = SitecoreContext.GetItem<ISiteSettings>(dataSourceId);

    return View(siteSettings);
}

return new EmptyViewResult();

You can figure this solution out (assuming you didn't already know how to do this) by deconstructing the GlassController on Github. You can see that the T GetDataSourceItem() is passing in a Datasource which is the id returned from RenderingContext.Current.Rendering.Datasource into the standard .GetItem method.

Also you asked what exactly is Rendering.Item and how is that different from the datasource on that rendering. The Rendering.Item is pretty much the same as calling Context.Item which would be the page you are on. Which the datasource would be the item directly assigned to the current rendering.

| improve this answer | |
  • Based on the current situation I can change the inheritance, what is the other way to do this? – tmp dev Jul 26 '17 at 1:05
  • I updated my answer to cover your concerns. – Dylan Young Jul 26 '17 at 2:16
  • Thanks for your comments, I noticed the following. Within a controller rendering Rendering.Item and Rendering.DataSource seem to refer to the same thing except one returns a complete item and the other returns only the id. So its not the same as Context.Item which returns the current page I guess. – tmp dev Jul 27 '17 at 22:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.