简体   繁体   中英

Is there any alternates Attribute for asp.net core enum model binding instead of EnumMemberAttribute?

There's a enum type:

public enum Cat {
    [EnumMember(Value = "white_cat")]
    WhiteCat,
    [EnumMember(Value = "black_cat")]
    BlackCat
}

but use as follow asp.net core 2.2 model binding, it will binding failure:

public class A {
    public Cat TheCat { get; set; }
}

public class XXXController : ControllerBase {
    public ActionResult XXX([FromForm] Cat cat) {
        // ...
    }
}

Reference: https://stackoverflow.com/a/58338955/3907561

public class EnumMemberConverter<T> : EnumConverter {
    public EnumMemberConverter(Type type) : base(type) { }

    public override object ConvertFrom(ITypeDescriptorContext context, 
                                       CultureInfo culture, 
                                       object value) {
        var type = typeof(T);

        foreach (var field in type.GetFields()) {
            if (Attribute.GetCustomAttribute(field, typeof(EnumMemberAttribute)) is EnumMemberAttribute attribute &&
                value is string enumValue &&
                attribute.Value == enumValue) {
                return field.GetValue(null);
            }
        }

        return base.ConvertFrom(context, culture, value);
    }
}

usage:

[TypeConverter(typeof(EnumMemberConverter<Cat>))]
public enum Cat {
    [EnumMember(Value = "white_cat")]
    WhiteCat,
    [EnumMember(Value = "black_cat")]
    BlackCat
}

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