More
Choose

Geting PreValues from Umbraco 7 Data Type

Some sample code to show how to get pre values for a Data Type

Read Post
Category:  Umbraco
Posted:  7th August 2018

I thought i would share the solution to getting the pre values from a Data Type, as the documentation for this on the Umbraco website seems to have been removed.

The code below is an edited version of what worked for me (to remove the project details).

You will need to replace NAME or name with your values to make this work correctly, however it should point in the right direction.

[ChildActionOnly]
[ActionName("NAME")]
public ActionResult NAME()
{
    return PartialView("~/Views/Partials/NAME.cshtml", new MODELNAME{NAME = GetSelectListForNAME()});
}

private SelectList GetSelectListForNAME()
{
    var preValueDataType = Umbraco.DataTypeService.GetPreValuesCollectionByDataTypeId(1301); //Change Data Type ID
    var preValues = preValueDataType.PreValuesAsDictionary.Values.Where(pdv => pdv.Value != "0");

    var namesList = preValues.Select(preValue => new SelectListItem
        {
            Value = preValue.Id.ToString(),
            Text = preValue.Value
        })
        .ToList();
    return new SelectList(namesList);
}

Model

public SelectList NAMES { get; set; }

public string NAME { get; set; }

Razor View

This will populate a drop down list

@Html.DropDownListFor(model => model.NAME, Model.NAMES.Items as List)