0

I have created a map which convert an enum to a SelectList by using a custom implementation of ITypeConverter.

public class DeliveryModeToSelectListTypeConverter : ITypeConverter<ProductDeliveryMode, SelectList>
{
    public SelectList Convert( ResolutionContext context ) {
        ProductDeliveryMode pdm = (ProductDeliveryMode)context.SourceValue;
        List<SelectListItem> items = new List<SelectListItem>();
        SelectListItem sli1 = new SelectListItem() {
            Text = StringEnum.GetStringValue( ProductDeliveryMode.DeliveryModeActivationByPin ),
            Value = ( (int)ProductDeliveryMode.DeliveryModeActivationByPin ).ToString(),
            Selected = (pdm == ProductDeliveryMode.DeliveryModeActivationByPin)
        };
        items.Add( sli1 );

        [...other enum members here...]

        SelectList sl = new SelectList( items, "Value", "Text", pdm );
        return sl;
    }
}

And then I have created a Map by using

Mapper.CreateMap<ProductDeliveryMode, SelectList>()
      .ConvertUsing( new DeliveryModeToSelectListTypeConverter() );
Mapper.CreateMap<Product, ProductViewModel>()
    .ForMember( p => p.DeliveryModeOptions, opt => opt.MapFrom( x => x.DeliveryMode ) )
    [...other members here...]
    .Include<ExperienceProduct, ExperienceProductViewModel>();
Mapper.CreateMap<ExperienceProduct, ExperienceProductViewModel>()
    .IncludeBase<Product, ProductViewModel>()
));

Everything seems to works very nice except from the fact that the Selected value of the SelectListItem does not maintains its value. I have been able to step into the code and the SelectListItem sli1 it's correctly created with the selected value equal to true.

Value when mapping

However when i check that value after a mapping the value is always false as you can see from the following screenshots.

Value after mapping

Where do I am wrong with this code?

Lorenzo
  • 29,081
  • 49
  • 125
  • 222

1 Answers1

1

The problem is when you create the select list:

SelectList sl = new SelectList( items, "Value", "Text", pdm);

You're passing the selected item as pdm of type ProductDeliveryMode, which is being compared against the Value property of type string.

From your comment below, the solution was to pass pdm as a string.

mfanto
  • 14,168
  • 6
  • 51
  • 61
  • Well, your suggestion did'nt worked. But actually made me thinking to a difference. When I am passing inline the `pdm` that is of type `ProductDeliveryMode` while the `Value` member of the `SelectListItem` object is of type string. I ended up with passing the `pdm` object after having it converted to string. And everything di worked! If you correct your answer I will be glad to accept it. Thank you. – Lorenzo Apr 04 '15 at 21:04
  • Oh great, I wasn't exactly sure how SelectList worked behind the scenes, but the different type for `pdm` is what made me suspicious. I will update the answer. – mfanto Apr 04 '15 at 21:07