0

I am struggling to get the selected value of a list inside a Sitecore Forms 9.1 custom submit action.

The value I am seeing is:

System.Collections.Generic.List`1[System.String]

From the various samples on the Internet - I have tried using:

return field?.GetType().GetProperty("Value")?.GetValue(field, null)?.ToString() ?? string.Empty;

and

var postedField = (IValueField)viewModel;
IValueField valueField = postedField as IValueField;
PropertyInfo property = postedField.GetType().GetProperty("Value");
object postedValue = (object)property != null ? property.GetValue((object)postedField) : (object)null;

Which works fine for text values, but not for the selected radio button or checkbox from a list.

I could just check if the type is a list/collection and iterate over the values but just wanted to check if there was something cleaner already out there.

2

As you mentioned it is working for text value so for dropdown you can use below code and similar condition you can use for radio button and checkbox using corresponding view model.

var field= GetFieldById(data.dropdownFieldId, formSubmitContext.Fields);
string dropdownValue=GetValue(field);


private static IViewModel GetFieldById(Guid id, IList<IViewModel> fields)
        {
            return fields.FirstOrDefault(f => Guid.Parse(f.ItemId) == id);
        }

private static string GetValue(object field)
        {

            if (field is DropDownListViewModel)
            {
                DropDownListViewModel dropdownField = field as DropDownListViewModel;
                string selectedtext = dropdownField.Value.FirstOrDefault();
                return selectedtext;
            }
             // Similar condition you can apply for checkbox using CheckBoxViewModel

            return field?.GetType().GetProperty("Value")?.GetValue(field, null)?.ToString() ?? string.Empty;
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.