How To Get The Current Page in Sitecore

When you start building any web project, one of the first things that you will need to do is get information about the current page to display related page data back to the website user. In today’s tutorial, I’m going to cover some of the basic API calls to achieve this.

Sitecore Instance

To get information about the current item, you can use the Sitecore Context. Like the normal HttpContext, the Sitecore context, as the name suggests, gives you information about the current request.

Sitecore.Context.Item 

The Sitecore.Context.item has a number of useful properties. For example, if you want to know if the current page is being viewed in a Sitecore preview, or, from the website you can use this code:

Sitecore.Context.PageMode.IsPreview

and

Sitecore.Context.PageMode.IsNormal

Get current page URL from Sitecore API

Using the Sitecore.Context we can then use the LinkManager to get the current pages Url like so:

var currentUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item);

Change is coming..

Ok, so for years and years the Sitecore context was the only way to get information about the current request, however, with the DMS and MVC using Sitecore.Context isn’t always the best approach.

Sitecore MVC Helpers

In our Razor views, we might want to get Sitecore information. Personally, I would strongly discourage doing this as it breaks the point of MVC. By using these helpers you are adding business logic into your views. It’s a much better technique to put all your Sitecore logic in View Models and pass them into your views. For reference, though, here are the helpers:

@Html.Sitecore().CurrentItem
@Model.Item
@Model.Rendering.Item
@RenderingContext.Current.Rendering.Ite

Page Context

if you are trying to write code about the current request in a rendering, you may want to look at the page Context. In the context of a rendering, the page item is the root item that will be rendered. In these instances you can use the pgeContext to get the information:

1
var page = PageContext.Current.Item;

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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