Thursday, May 5, 2016

Experience Editor Context Item Issue

Hi All,
Currently I am working on a project task & found a wearied issue might be some of my colleague are aware from it. Issue is that when I am getting context item using
"Sitecore.Context.Item". It's work fine for normal mode & I am capable to perform my custom logic on context item but when I saw in Experience editor It always take home item when i call "Sitecore.Context.Item", I try to debug the code & found in normal mode I am getting the context item(On which item i visited or current item) but in Experience mode it always take the Home Item. 
So I look into the issue & try to resolve that & found that "Sitecore.Context.Item" not getting the context item in Experience mode so I found very good solution for that I just show the code which is useful for getting the context item in both mode(normal & Experience Editor mode). Code are below:
public Item GetContextItem()
        {
            Item item = null;
            if (Sitecore.Context.PageMode.IsExperienceEditor
 || Sitecore.Context.PageMode.IsExperienceEditorEditing
 || Sitecore.Context.PageMode.IsPreview)
            {
                if (Request.UrlReferrer != null)
                {
                    UrlString url = new Sitecore.Text.UrlString(Request.UrlReferrer.ToString());
                    var id = url.Parameters["sc_itemid"];
                    item = Sitecore.Context.Item;
                    // if a query string ID was found, get the item for page editor and front-end preview mode
                    if (!string.IsNullOrEmpty(id))
                    {
                        item = Sitecore.Context.Database.GetItem(id);
                    }
                }
            }
            else
            {
                item = Sitecore.Context.Item;
            }
            return item;
        }
Hope this is helpful for you. Please give suggestion and feedback both are welcome.

Regards

No comments:

Post a Comment