• Published
  • 1 min

Saving dictionary items on a commerce contact

Saving dictionary items on a customer contact i EPiServer Commerce is not well documentet, so this blog post provides the code you need to get started

I had some troubles saving dictionary items on my customer contact objects, and my best friend, Mr. Google, could not help me... Fortunately, there are EPiServer employees around to provide help :) The following code examples are originaly from Petter Sørby. I have changed it to match my requirements.

The dictionary items are saved different wether it is a single value dictionary or a multiple value dictrionary. The single value version requires an int (or string), while the multiple value requires an array of int (or string).

The following code fetches the handle(s) for the selected item(s) and set that value for the given contact field. The dictionary item sort index starts at 1 instead of 0, so it is important to use the enum handle value and not a selected index or some other "custom" int.

private void AddMultipleValue(CustomerContact contact, string fieldType, string fieldName, string [] values)
{
 var field = DataContext.Current.GetMetaFieldType(fieldType);
 contact[fieldName] = values.Select(value => GetHandleFromDictionary(field, value)).ToArray();
}

private void AddSingleValue(CustomerContact contact, string fieldType, string fieldName, string value)
{
 var field = DataContext.Current.GetMetaFieldType(fieldType);
 contact[fieldName] = GetHandleFromDictionary(field, value);
}

private int GetHandleFromDictionary(MetaFieldType fieldType, string value)
{
 var enumValue = fieldType.EnumItems.FirstOrDefault(i => i.Name.Equals(value));
 if (enumValue == null)
 {
  throw new System.ArgumentException(@"Value not found in Dictionary", value);
 }
 return enumValue.Handle;
}

You can then use the methods like this:

 var contact = CustomerContext.Current.GetContactForUser(Membership.GetUser("username"));
AddSingleValue(customerContact, "MaritalStatus", "MaritalStatus", "Married");
AddMultipleValue(customerContact, "MusicPreferences", "MusicPreference", new string[] {"Pop", "Rock"});

The following screenshot describes the differnce between field type and field name.

Image shows where you find the field type and field name in a dictionary item in EPiServer Commerce