Umbraco 7 when to use @Umbraco vs @CurrentPage vs @Model in Razor views?

Iain picture Iain · Oct 1, 2014 · Viewed 15.1k times · Source

As the title says, when should I use @Umbraco, @CurrentPage or @Model in Razor views to get properties from a node.

@Model.Content.GetPropertyValue() returns a strongly typed object, whereas @CurrentPage returns a dynamic object. However, with @Umbraco I can get a dynamic (@Umbraco.Content()) or a strongly typed object (@Umbraco.TypedContent()).

Can @Umbraco helper do everything that @CurrentPage and @Model can do? When should I be using which, and why?

Answer

dampee picture dampee · Oct 2, 2014

You answered most of your question yourself. @Model and @CurrentPage are the same except @CurrentPage is dynamic. Both return the current page. That means that, if you interit your views from UmbracoViewPage, you can not use @CurrentPage because this is only available on the UmbracoViewTemplate. Personally I like @Model more than @CurrentPage, but it's a personal choice

@Umbraco is a completely different beast. It does not return the current page, but it has a bunch of methods to get other content, media and members in different ways (e.g. xpath). But also templating and misc methods like:

  • Umbraco.If(condition, trueValue [, falseValue])
  • Umbraco.Trunctate // limit text size
  • Umbraco.StripHtml // remove html tags
  • Umbraco.Search // full text search

To know more about the @Umbraco, visit the Umbraco helper documentation

E.g. If you got an image ID from the current node using

var imgId =  @Model.Content.GetPropertyValue<string>("img")

then you could use @Umbraco.TypedMedia(imgId) to get the image IPublishedContent object.

Update: Next to @Umbraco.Field("propertyAlias") which is one of the template helpers, you can also use @Umbraco.Field( x, "propertyAlias") where x is an IPublishedContent. This will always return an IHtmlString which makes it impractical for other programming efforts, but makes the Umbraco.Field() a very nice helper method to return properties.

Update 2: Starting from version 7.4, There is a modelBuilder which allows you to define UmbracoTemplatePage<ContentModels.HomePage> and use @Model.Content.BodyText later on. Starting from Umbraco v8 (on the roadmap), support for dynamics (CurrentPage on UmbracoTemplatePage) is said to be dropped. So prepare by using ModelsBuilder and UmbracoViewPage<MyModel>.

Update 3: Starting from version 8, there will be only an UmbracoViewPage. That means that CurrentPage will not be available anymore. Try to use the "models builder" approach to be future proof or read the first v8 documentation about this topic.