.NET Core - Is there a way to set an enum to have a default value when using a Select Tag Helpler?

Viewed 4711

So I'm converting an enum to a dropdown list via the .NET Core tag helper. It's pretty standard.

Enum

public enum DistanceType
{
    [Display(Name = "1 Mile")]
    [Description("1")]
    OneMile = 1,

    [Display(Name = "5 Miles")]
    [Description("5")]
    FiveMiles = 2,

    [Display(Name = "10 Miles")]
    [Description("10")]
    TenMiles = 3,

    [Display(Name = "20 Miles")]
    [Description("20")]
    TwentyMiles = 4
}

View

<select asp-for="EnumDistanceType" asp-items="Html.GetEnumSelectList<DistanceType>()">
</select>

So what I want to do is every time I render this enum into a dropdown list I want it to select, by default, a value other than the first one. So for example, every time I render the dropdown it displays "5 Miles" to the user instead of "1 Mile". I don't want to change the order of the enum though, I want the dropdown to be on the second object.

Is there some easy way to do this by just using a tag on the enum? Or if not in the enum is there some way to do this in the tag helper?

Thanks.

3 Answers
    public static class HtmlHelperExtensions
    {
        public static IEnumerable<SelectListItem> GetEnumSelectListWithDefaultValue<TEnum>(this IHtmlHelper htmlHelper, TEnum defaultValue) 
            where TEnum : struct
        {
            var selectList = htmlHelper.GetEnumSelectList<TEnum>().ToList();
            selectList.Single(x => x.Value == $"{(int)(object)defaultValue}").Selected = true;
            return selectList;
        }
    }

Usage:

<select asp-for="EnumProperty" asp-items="Html.GetEnumSelectListWithDefaultValue<SomeEnum>(defaultValue: SomeEnum.SomeEnumValue)">
</select>

This works for me. Have a look :)

<select asp-for="EnumDistanceType" asp-items="Html.GetEnumSelectList<DistanceType>()">
    <option selected value="2">FiveMiles</option>
</select>
Related