1

I'm trying to build a custom admin utility page which will add renderings to a page. The action happens in an Ajax call and so the Sitecore.Context is unavailable. I do have the pageItem though.

LayoutField layoutField = new LayoutField(pageItem.Fields[FieldIDs.LayoutField]);
LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
var contextDb = Sitecore.Context.Database;
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());

In the above code, contextDb is null & deviceDefition throws an error because Sitecore.Context.Device is null.

Is there a way to programmatically set the Sitecore.Context or get it from the pageItem.

Using Sitecore 9.3

  • 2
    Instead of using Sitecore.Context.Database just use pageItem.Database. There is no way of getting the device from the request of admin page. Easiest way is to pass deviceId to your ajax request – Marek Musielak Oct 8 at 7:00
  • @MarekMusielak I have tried getting Sitecore.Context.Device.ID in the Page_Load event of the aspx custom-admin-page. It is null. Should this page inherit from any other class. I have created many admin pages before that do item manipulations like create/update etc. But this is the first one that needs Sitecore.Context. Please suggest. – Qwerty Oct 8 at 7:21
  • 2
    How can Sitecore possibly know which device you need? It's not there on admin page. But I suppose you always want default device on your admin page. In that case, you can just hardcode the value, right? – Marek Musielak Oct 8 at 7:29
1

If you have the pageItem which is an instance of Sitecore.Data.Items.Item class, you can wrap your code into a DatabaseSwitcher and DeviceSwitcher

        using (new DatabaseSwitcher(pageItem.Database))
        {
            using (new DeviceSwitcher(pageItem.Database.Resources.Devices.GetAll().Where(t=>t.Name.Equals("default",System.StringComparison.OrdinalIgnoreCase)))))
            {
                // Add your code block here
            }
        }
| improve this answer | |
0

Sitecore can do all this for you as well without the need to write any custom code when you pass the Guid of the item in sc_itemid query string in your Ajax call. I just tested and this will get Sitecore.Context.Device populated with default device.

Note that you might need more querystrings if you are after additional info. For example Sitecore cannot determine the context site unless you also specify sc_site

| improve this answer | |

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.