In this tutorial, you will learn how to query Umbraco CMS for page related data. You might think that querying for data is simple, however, in V8 there are a number of different ways to query for content. I think that these different methods can make it confusing for developers who are trying to master Umbraco. Especially when you fail to get a code snippet you find online to work and you do not understand why!
The aim of this tutorial is to help you understand these nuances. The important thing to remember is that you query content from the frontend cache. The frontend cache can be accessed via the UmbracoContext
. The front-end cache is stored in something called NuCache. It can be accessed from UmbracoContext
via the Content
property. If you look at its type, then you will see it is of type, IPublishedContentCache
. You may naturally think a shortcut to accessing the content cache would be to inject this interface directly into your custom classes, you would be wrong.
If you tried to inject this interface an exception would be thrown. Instead, you need to access the cache indirectly. In this tutorial, we will cover four different ways of accessing the cache, these are:
UmbracoHelper
IPublishedContentQuery
UmbracoContext
IUmbracoContextFactory
IPublishedContentQuery
Another way of accessing the cache is via IPublishedContentQuery
:
Umbraco Helper
Another way of accessing the cache is via UmbracoHelper
. The code to access the cache this way, looks like this:
IUmbracoContextFactory
The safest way to access the front-end cache is to use the IUmbracoContextFactory
. The reason this service exists is that the context uses the HttpRequest object to work correctly. Imagine you tried to use the UmbracoContext
within global.asax
. This would cause an error as the HttpContext
object would not have been created. This service helps you to write safe code, as it will only give you access to UmbracoContext
if everything has been set-up correctly:
RenderMvcController
When you are within RenderMvcController
, SurfaceController
, or any of the other base types, then you can access the UmbracoContext
using the exposed public property UmbracoContext
:
View
In a view, if the backing type inherits from UmbracoViewPage
then you will have access to the UmbracoContext
and UmbracoHelper
. You only get access to both of these when you use @inherit UmbracoViewPage<>
. When you pass a view model into a view file you will need to use @model
and you will not get access to either service. This is OK because following good MVC principles, all your logic should be added within a controller and passed down into the view rather than done within the view-level itself. This is how the context is referenced in a view: