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.
Getting Current Page Information From A Controller
Now Umbraco is compatible with MVC, it is good practice to move as much logic out of the Umbraco database and views and move it into your view models and controllers. Doing this means you can provide better test coverage in your unit tests, you can store more data in your source control repository, and you can have a better continuous deployment process to your production servers.
When you start writing more code in your controller, you will need to know which Umbraco API’s to use to get information about the current page. 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);
This is the simplest way to get information about the current page. First, we get the current pages ID, using the CurrentPage.Id property to get the current pages ID, then the Umbraco helpers TypedContent() method to get the page data out of the database.
If you don’t care about getting the current page ID, you can use this even more streamlined snippet of code to get the current page:
var current = (CurrentPage);
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.