I’ve been working on a website that uses data from a cloud based Dynamics 365 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. We needed to find out how to dynamically retrieve the OptionSet
values in C# to populate our dropdown control. 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.
OptionSet C# – use RetrieveAttributeRequest to get metadata
Sure we could have created a static list of values, but that would be a terrible idea. If the underlying values were updated, added, or removed then our website wouldn’t reflect those changes.
In your C# code, use RetrieveAttributeRequest and RetriveAttributeResponse. We can then use the AttributeMetaData returned, which in turn contains a list of OptionSet values.
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; }
Map the data to build the C# OptionSet objects
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" }
…. and this can be used to populate a dropdown control.