Computer Magic Logo
Model.Content

Saturday, August 8, 2015

Published by Aristotelis Pitaridis

We saw how to use the CurrentPage object in order to access the dynamic representation of the current page. Let’s see how to use the Content property of the Model object in order to access the typed representation of the current page. First we will see the fixed properties of the page which has exactly the same syntax like we have with CurrentPage object.

@Model.Content.Id
@Model.Content.Name
@Model.Content.UrlName
@Model.Content.Url
@Model.Content.CreateDate
@Model.Content.UpdateDate
@Model.Content.CreatorName
@Model.Content.WriterName
@Model.Content.Level
@Model.Content.Path
@Model.Content.SortOrder

When we use the Content property of the Model object for accessing custom properties we have a problem which will generate an error message if we are not careful. We use the GetPropertyValue member function of the Content property and the syntax is the following:

@Model.Content.GetPropertyValue<string>("description")

As we can see we define the type of the property we want to access which in our case is string. The problem is that if we try to execute this command we will have an error message. This happens because we have the less than and greater than characters which confuses the Razor engine and make it believe that this is an html tag. In order to resolve this problem we can wrap the entire command inside a pair of parenthesis.

@(Model.Content.GetPropertyValue<string>("description"))

Now the code works and we can get the value of the property. A good practice is to check if a value has defined for the property because if we have not defined a value in one of our pages it may have as a result some pages of our site to display error messages. In order to avoid such scenarios we can use the following code in order to display the contents of a custom property.

@if (CurrentPage.HasValue("description"))
{
    @((Model.Content.GetPropertyValue<string>("description")))
}