How To Check That A Page Contains A Property

Often when working within Umbraco, you will work need to work with content and the IContent objects.  When you work with IContent you don't necessarily know the document type you are working with.  If you try and use GetValue() and the property doesn't exist, Umbraco will throw a 'The given key was not present in the dictionary' exception.  If you find yourself in this situation you  can use 'HasProeprty'

var content = IContent;
content.HasProperty("alias");

Just because you use HasProperty() it doesn't mean the property contains a value and hasn't been set.  When this happens you can use:

var content = IContent;
content.GetValue("alias");

So, if you need to check that a property exists and has been set, you could do something like this:

var content = IContent;
content.HasProperty("alias") && content.GetValue("alias") != null;

If you are working IPublishedContent you can do a something similar and use HasValue() instead.

var publishedContent = IPublishedContent;
publishedContent.HasValue(variable).

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top