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 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:


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!

Tagged with: ,