简体   繁体   中英

AutoMapper map Enum to SelectList - Selected value not working

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 .

映射时的价值

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

映射后的价值

Where do I am wrong with this code?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM