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.
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:

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:

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:
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

Back to top
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-35662136-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + ''; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();