I'm using @Html.EnumDropDownListFor()
to display a dropdown list for my enums. I want to set the selected value to one of the enum values. The question asked here is very similar to what I'm asking here but the answer provided there, did not work in my case.
What I have tried so far :
Enum :
public enum Region
{
Europe = 0,
NorthAmerica = 1,
Korea = 2,
China = 3,
Taiwan = 4
}
Controller Action:
(where i set the value of my enum)
public ActionResult Index(Region region = Region.Europe)
{
var model = new RealmViewModel();
model.Realms = realmService.GetAllRealmsByRegion(region);
model.Region = region;
return View(model);
}
View Model:
public class RealmViewModel
{
public IEnumerable<Realm> Realms { get; set; }
public Region Region { get; set; }
}
View:
(where I'm showing the enum as dropdownlist and want to set the selected value)
@model RealmViewModel
<div class="form-group">
<label for="region-input">Region</label>
@Html.EnumDropDownListFor(model => model.Region, new { @class = "form-control", @id = "region-input" })
</div>
Inside the rendered view, the dropdown list is always set on the first enum value i.e Europe
. Even when I'm calling Index()
action with a realm other than Europe
, and Debugger shows that Model.Region
is indeed some other value like Korea
, the drop down again shows Europe
selected. Based on the other question, because I'm setting the model.Region
value inside my controller index
action, then the @Html.EnumDropDownListFor()
should select that enum value as default, but for some reason it doesn't work in my case.
Why can't I set the EnumDropDownListFor selected value this way?
Update:
I'm calling the controller action like this :
/Home/Index?region=Korea
@Ric's answer suggested to call the action like : /Home/Index?region=2
And then it worked as expected. So the real question should be: Why it doesn't work when I'm calling the action by the string value of the enum, but it only works when I call the action by the integer value of the enum?
I debugged both calling methods, and I can say that all the values in both methods are identical. So I don't understand why the first one doesn't work as expected.