简体   繁体   English

AutoMapper将Enum映射到SelectList-选择的值不起作用

[英]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. 我创建了一个映射,该映射通过使用ITypeConverter的自定义实现将枚举转换为SelectList。

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 然后我使用创建了一个Map

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. 除了SelectListItemSelected值不保持其值的事实以外,其他所有内容似乎都工作得很好。 I have been able to step into the code and the SelectListItem sli1 it's correctly created with the selected value equal to true . 我已经能够进入代码,并且SelectListItem sli1已正确创建,且所选值等于true

映射时的价值

However when i check that value after a mapping the value is always false as you can see from the following screenshots. 但是,当我在映射后检查该值时,该值始终为false如以下屏幕截图所示。

映射后的价值

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 . 您正在将所选项目作为ProductDeliveryMode类型的pdm传递,并将其与string类型的Value属性进行比较。

From your comment below, the solution was to pass pdm as a string. 从下面的评论中,解决方案是将pdm作为字符串传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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