Umbraco – The GetPreValues Method Using Datatype Name

PreValues are the data values stored in Umbraco datatypes, such as a Dropdown list or a Checkbox list. If you use such a datatype (e.g. a pre-populated dropdown list) in your Umbraco installation, and you’re retrieving your Umbraco data from the application cache then you will generally not need to worry (or even know!) about PreValues as the cache would serve up the selected value for you. However if you’re accessing your Umbraco data directly from the database (and yes I know that it’s not as quick as accessing the cache, but sometimes you just have to access the database!) you will need to understand how to get the PreValues and the corresponding data out of them.

Most of the examples you see on how to get PreValues and their corresponding data (including this one from our.umbraco.org) usually involve hard-coding the ID of the datatype like this:

int categoryDataTypeNodeID = 1210;

or like this:

XPathNodeIterator iterator = umbraco.library.GetPreValues(10611);

I prefer to use the datatype name rather than hard-coding the ID though, as the ID could change if you set up a new environment or a new database. So here’s how I get my PreValues.

First I get the datatype by name:

var dataType = Services.DataTypeService.GetDataTypeDefinitionByName("My Datatype Name");

Then I get the PreValues for that datatype using the GetPreValues() method as seen above, which returns an XPathNodeIterator object:

var preValuesFromDataType = library.GetPreValues(dataType.Id);

Now once you have this XPathNodeIterator object you can move through the iterator and do whatever you need to do with those values. In the following example I move through my PreValues and add them to a list of SelectListItem objects in a controller, so I can use them within a Select List control in a form:

preValuesFromDataType.MoveNext();

var myIterator = preValuesFromDataType.Current.SelectChildren(“preValue”, “”);

while (myIterator.MoveNext())
{
  model.Dropdown.Add(new SelectListItem { Text = myIterator.Current.Value, Value = myIterator.Current.GetAttribute("id", "") });
}

The important thing to note is that you need to call the MoveNext() method on your XPathNodeIterator (line 1 above) before you do the assignment statement (line 2 above), otherwise your “myIterator” object will be null and you won’t get anything out of it! But apart from that, it’s pretty straight forward once you know!

Posted in Code, Umbraco Tagged with: ,

About Maff

Maff Rigby

I'm a certified .Net, Umbraco and AngularJS freelance developer with over 15 years experience in the IT industry. As well as writing code I love to teach; I run a number of workshops and 1-1 coaching sessions on Angular JS and Umbraco, and share what I know and learn here!

I’m social (ish)

Connect with me on LinkedIn, follow me on Twitter, or fail to find me on Facebook.