Developer forum

Forum » Development » Dropdown option label from a value using Items

Dropdown option label from a value using Items

Nuno Aguiar Dynamicweb Employee
Nuno Aguiar
Reply

Hi,

 

I'm struggling to find a way to return the label of a dropdown option using the API.

 

Use case:

  • I have an Item
    var item = Dynamicweb.Services.Items.GetItem("MyItem", "123");
  • I get the value of the field x.GetString("MyDropdownField") returns the string
    var fieldValue = x.GetString("MyDropdownField");
  • This gives me the value "3" (for example), but I want the label "Hello world";

 

Now how do I get the label for that value? I tried a few things, but nothing on the API seems to stand out.

 

I know that with ModelViews I have .GetList() and that's contains the properties SelectedValue and SelectedName. But I can't seem to cast an Item into an ItemViewModel. 

 

Best Regards,

Nuno Aguiar

 


Replies

 
Morten Bengtson Dynamicweb Employee
Morten Bengtson
Reply
This post has been marked as an answer

Hi Nuno,

The list options are part of the meta data for each item type.
You can find the selected option by value and then get the name (label) from there. Something like this (not tested):

var item = Dynamicweb.Services.Items.GetItem("MyItem", "123");
var value = item["MyDropdownField"];
var meta = ItemManager.Metadata.GetItemType(item);
var field = meta.Fields.Find("MyDropdownField");
var options = field.Options.Values;
var selectedOption = options.FirstOrDefault(o => Equals(value, o.Value));
var selectedOptionName = selectedOption.Name;

You probably need to include some null checks :)

Best regards,
Morten

Votes for this answer: 1
 
Nuno Aguiar Dynamicweb Employee
Nuno Aguiar
Reply

Hi Morten,

 

This is perfect. Worked like a charm thanks. If you guys could implement a method to do this on the Item class would be helpful. I created a method to help with get what I want

private string GetSelectLabelFromValue(string itemType, string itemId, string fieldSystemName, string value)
{
    return GetSelectLabelFromValue(item, fieldSystemName, value);
}

 

private string GetSelectLabelFromValue(Item item, string fieldSystemName, string value)
{
    var meta = ItemManager.Metadata.GetItemType(item);
    var field = meta.Fields.Find(fieldSystemName);
    var options = field.Options?.Values;
    if (options == null) return "";
    
    var selectedOption = options.FirstOrDefault(o => Equals(value, o.Value));
    return selectedOption?.Name;
}

 

Best Regards,

Nuno Aguiar

 

You must be logged in to post in the forum