3

I'm working in an ASP.NET MVC application. The database I'm working with is a legacy database.

In my code, I have an Enum that looks like this:

public enum Fruit
{
    Apple = -1,
    None = 0,
    Orange = 1
}

I cannot change that, and when I try to do this in my Razor View:

@Html.EnumDropDownListFor(m => m.Fruit, "Select a fruit", new { @class = "form-control" })

The view loads with None always selected, when I want it to load on Select a fruit

What is the cleanest way of achieving this? I can hack it in JavaScript, but is there a better way?

J86
  • 14,345
  • 47
  • 130
  • 228
  • 1
    Is the model property nullable? I.e.: `public Fruit? Fruit { get; set; }` – juunas Mar 13 '17 at 13:40
  • No, but I can make it so and I tried, but no success still – J86 Mar 13 '17 at 14:11
  • 1
    nullable should work maybe you didnt build when changing it to nullable – Usman Mar 13 '17 at 14:19
  • I did debug, it starts with `0` even when I have `Fruit? Fruit`. Do I need to explicitly tell it that its value should be `null` like [mentioned here](http://stackoverflow.com/a/4337236/613605)? – J86 Mar 13 '17 at 14:37
  • Never mind, even when I set it to `null` explicitly, it still chose to go to `None` which has value `0` :( – J86 Mar 13 '17 at 14:41
  • 1
    thats stange i tested it and it was selecting Select a fruit as default in nullable – Usman Mar 13 '17 at 16:17
  • @Usman in your enum was the value of any of your enum fields `0`? – J86 Mar 14 '17 at 10:29
  • i took your code and tested it – Usman Mar 14 '17 at 11:10

1 Answers1

0

I was able to get the default text selected by making the Fruit Enum nullable in my view model:

public class FruitContainer
{
    public Fruit? Fruit;
}

In the view:

@ModelType FruitContainer
@Html.EnumDropDownListFor(m => m.Fruit, "Select a fruit", new { @class = "form-control" })

If the drop down list still does not select the default text, you might make sure that any model you are passing to the view from the controller does indeed have its Fruit property set to null.

vidvid
  • 1
  • 1
  • 2