On every Umbraco 7 build, you will undoubtedly need to get information about the current page, create a link to the search page, the contact us page. Luckily, Umbraco provides us several API calls to achieve this. In this guide, I'm going to hopefully explain the different options and where and when you should use them.
Getting Current Page Information From A Controller
When we work with Umbraco there are two main ways of getting content, one is via a cache and is pretty quick. The other is via the database. and consequently, consumes more resources. If you're wondering why it exists, then the answers simple, if you only read data from Umbraco use the cache. f you need to save content manually, or, work with unpublished page then you will need to work with content directly in the database.
Getting The Current Page Via The Cache
In this method, we want to return the current page as an IPublishedContent. We do this via the UmbracoHelper, like so:
var currentPageId = UmbracoContext.Current.PageId; Umbraco.TypedContent(currentPageId);
Depending on where you're writing your code, e.g. in a controller then you might have to manually create the Umbraco helper, like so:
var currentPageId = UmbracoContext.Current.PageId; var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); IPublishedContent content = umbracoHelper.TypedContent(currentPageId);
Getting The Current Page Via The Database
To get the content via the database, so you can write to it as well, you need to use a different API, like so:
var currentPageId = UmbracoContext.Current.PageId; IContent content = ApplicationContext.Current.Services.ContentService.GetById(currentPageId);
The Legacy Way (Umbraco 6 and below)
The first way of getting the current page is an older method and isn't considered best practice now:
Document document = new Document(Node.GetCurrent().Id);
Node.GetCurrent() is now a legacy API and in Umbraco 7 it is not recommended to use it. Originally, Node got the Id directly from the database, instead of the XML cache. However, now if you implement the code above in your project and hover your mouse over the 'Document' type you will see a deprecated error. If you stumble across this now, you know not to use it. Now I've covered the API you shouldn't use, it's time to go over the recommended approaches:
var id = CurrentPage.Id; var currentNode = Umbraco.TypedContent(id);
Getting The Current Page In A View
In the view, things are also pretty easy, as long as your view is inheriting from 'UmbracoTemplatePage' You can use @CurrentPage directly to get a dynamic method, or you can use @Model.Content to get a type-safe helper. To get the ID from example, you could use either of the following:
In today's guide, we've gone over some of the ways of getting data from Umbraco. The older Node/Document way is now obsolete. Instead, it's recommended to use the CurrentPage and the TypedContent methods.