Getting prevalues for dropdown lists in Umbraco

Umbraco is awesome (in our humble opinion) but one of the most frustrating things about developing with it is often the documentation, something which umbraco themselves are making strides to address as we speak.

With that in mind, something that took me a while to find out in the latest version of Umbraco is simply get the values of a dropdown list. Usually if you pull these directly from your model you get a bunch of Id’s rather than the actual string values. Hopefully this will save you some time.

This handy two liner can help out! You’ll need to reference “using umbraco.cms.businesslogic.datatype”

//get the data type name from the backoffice under developer -> datatypes
var datatype = Umbraco.DataTypeService.GetDataTypeDefinitionByName("Data Type Name");
var preValues = Umbraco.DataTypeService.GetPreValuesByDataTypeId(datatype.Id);

Now you have the prevalues, you can populate a select list:

var selectList = new List();

foreach (var item in preValues)
{
    selectList.Add(new SelectListItem()
    {
        Disabled = false,
        Selected = false,
        Text = item,
        Value = item
    });
}

//if you dont want to modify any of the properties of the select list items you can simply do
var selectList = new SelectList(preValues);

//sometimes theres an annoying "0" in the list which i believe is a default prevalue, you can get rid of this by:
var selectList = new SelectList(preValues.Where(m=>m!="0"));

And display it in your view as follows:

//m.SelectValue should be a property on your model to hold the value selected by the user, in this case a string
@Html.DropDownListFor(m => m.SelectValue, Model.SelectList, new { @class = "myClasses" })
back to blog

Related posts