Umbraco 13: Get Dropdown Value From A Custom Member Type
- Published on
- -2 min read
I've been working with custom functionality for registering and authenticating external site users in Umbraco 13 using its Members feature.
A custom Member Type was created so I could create field properties to specifically store all member registeration data. This consisted of Textboxes, Textareas and Dropdown fields.
Getting values for fields in code is very straight-forward, but I encountered issues in when dealing with fields that consist of preset values, such as a Dropdown list of titles (Mr/Mrs/Ms/etc).
Based on the Umbraco documentation for working with a Dropdown field, I should be able to get the selected value through this one line of code:
@if (Model.HasValue("title"))
{
<p>@(Model.Value<string>("title"))</p>
}
When working with custom properties from a Member Type, the approach seems to be different. A GetValue()
is the only accessor we have available to us to output a value - something we are already accustomed to working in Umbraco.
IMember? member = memberService.GetByEmail("johndoe@gmail.com");
string title = member.Properties["title"].GetValue()?.ToString(); // Output: "[\"Mr\"]"
However, the value is returned as a serialized array. This is also the case when using the typed GetValue()
accessor on the property:
IMember? member = memberService.GetByEmail("johndoe@gmail.com");
string title = member.GetValue<string>("title"); // Output: "[\"Mr\"]"
The only way to get around this was to create a custom extension method to deserialize the string array so the value alone could be output:
public static class MemberPropertyExtensions
{
/// <summary>
/// Gets the selected value of a Dropdown property.
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
public static string? GetSelectedDropdownValue(this IProperty property)
{
if (property == null)
return string.Empty;
string? value = property?.GetValue()?.ToString();
if (string.IsNullOrEmpty(value))
return string.Empty;
string[]? propertyArray = JsonConvert.DeserializeObject<string[]>(value);
return propertyArray?.FirstOrDefault();
}
}
It's a simple but effective solution. Now our original code can be updated by adding our newly created GetSelectedDropdownValue()
method to the property:
IMember? member = memberService.GetByEmail("johndoe@gmail.com");
string title = member.Properties["title"].GetSelectedDropdownValue();
Useful Information
Before you go...
If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!
Leave A Comment
If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.