Search code examples
c#asp.net-coreenumsasp.net-core-tag-helpers

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


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.


Solution

  • You need to set value for EnumDistanceType property for your model instance.

    Let's say your model class is

    public class DistanceViewModel
    {
        public DistanceType EnumDistanceType { get; set; }
    }
    

    Then your controller action may be:

    public IActionResult DistanceOption(int id)
    {
        var model = new DistanceViewModel();
        model.EnumDistanceType = DistanceType.FiveMiles;
        return View(model);
    }