Home » C# » Dynamics CRM dataverse – how to get a list of OptionSet values in C#

Dynamics CRM dataverse – how to get a list of OptionSet values in C#

I’ve been working on a website that uses data from a cloud based Dynamics CRM system lately, and one of the requirements involved us building an edit form for one of the entities. This particular entity had 3 different statuses – draft, active, cancelled and we needed to give the user a dropdown so that they could select the appropriate option. Sure we could have created a static list, but that would be a terrible idea – if the underlying values were updated, added, or removed then our website wouldn’t reflect those changes. So we neeeded to find out how to dynamically get those OptionSet values to populate our dropdown control, and it was surprisingly difficult to find the answer although the solution is fairly straightforward. Hopefully by sharing the solution here I can save you the time it took me to find the answer!

Use RetrieveAttributeRequest to get OptionSet metadata

By using RetrieveAttributeRequest and RetriveAttributeResponse, enables you to use the AttributeMetaData returned, which in turn contains a list of options.

 private async Task<List<OptionSetDTO>> GetOptionSetData(string entityName, string propertyName)
  {
   var attributeRequest = new RetrieveAttributeRequest
   {
     EntityLogicalName = entityName,
     LogicalName = propertyName,
     RetrieveAsIfPublished = false
   };

   RetrieveAttributeResponse response = (await 	GetOrganizationService()).Execute(attributeRequest) as RetrieveAttributeResponse;
	
   EnumAttributeMetadata attributeData = (EnumAttributeMetadata)response.AttributeMetadata;

   var optionList = (from option in attributeData.OptionSet.Options
                     select new OptionSetDTO(
                       option.Value,
                       option.Label.UserLocalizedLabel.Label))
     .ToList();
	return optionList;
 }

You’ll notice I map the option values into a simple object called OptionSetDTO, and that looks like this:

public class OptionSetDTO
{
  public OptionSetDTO(int? _value, string _name)
  {
    Value = _value;
    Name = _name;
  }
  public int? Value { get; set; }
  public string Name { get; set; }
}

That reusable method can be used like this to return a List of options:

List<OptionSetDTO> optionList = await GetOptionSetData("entityName", "propertyName");

The list of options returned then looks like this:

    {
      "value": 174640001,
      "name": "Draft"
    },
    {
      "value": 174640002,
      "name": "Active"
    },
    {
      "value": 174640003,
      "name": "Cancelled"
    }