Retrieving DropDownList Values in Razor or C#

Recently I needed to update the value of an Umbraco DropDownList property in code based on a value instead of the key that's automatically assigned by the Prevalue Editor.  I came across this but it discusses retrieving values for XSLT specifically.  In my scenario I needed to find a specific key.

The simplest way to do this is with XML to Linq.  In the example below I'm using the property's DataTypeDefinition to retrieve the relevant prevalue collection instead of hard-coding the Id of the DropDownList.  This means I have full flexibility in case something changes in the future:

if (p.getProperty("status") != null)
{
    var status = p.getProperty("status");

    status.Value = XElement.Parse(library.GetPreValues(status.PropertyType.DataTypeDefinition.Id).Current.OuterXml)
                           .Descendants("preValue").FirstOrDefault(pv => pv.Value == "On Offer").Attribute("id").Value;

    p.Save();
}

Note I could also have written it like this in Linq notation:

status.Value = (from pv in XElement.Parse(library.GetPreValues(status.PropertyType.DataTypeDefinition.Id).Current.OuterXml).Descendants("preValue")
                       where pv.Value == "On Offer"
                       select pv.Attribute("id").Value).FirstOrDefault();

 That's all there is to it.

1 comment for “Retrieving DropDownList Values in Razor or C#”

  1. Posted Friday, December 06, 2013 at 2:23:44 PM

    We can check that an image or paragraph exists by the return value of the SelectSingleNode or SelectNodes methods making it very easy to conditionally display the image or a placeholder if desired, for example.

Post a comment