Search code examples
asp.net-mvc-4enumshtml.dropdownlistforselected

MVC DropDownList NOT setting selected


I have a View for an Update operation, and I have a enum property of my Model:

public enum DeliveryStatusType
{
    Active = 1,
    Deactive = 2,
}

Basically, I populate the enum and using a DropDownList. To understand what is going on, I simplified it and posted here as simple as possible.

I've tried both Html.DropDownList and Html.DropDownListFor and here are the Views:

1st example (not setting the selected here):

@Html.DropDownListFor(model => model.DeliveryStatus, new SelectListItem[] {
        new SelectListItem { 
            Selected = false, 
            Text = "Active Delivery", 
            Value = "1" },
        new SelectListItem { 
            Selected = true, 
            Text = "Deactive Delivery", 
            Value = "2" }}) //Notice that I manually set the 2nd true

2nd example (not setting the selected here):

@Html.DropDownList("DeliveryStatus", new SelectListItem[] {
        new SelectListItem { 
            Selected = false, 
            Text = "Active Delivery", 
            Value = "1" },
        new SelectListItem { 
            Selected = true, 
            Text = "Deactive Delivery", 
            Value = "2" }}) //Notice that I manually set the 2nd true

But, what I realized is that when I set the name and the id of the SELECT html element other than DeliveryStatus (lets say DeliveryStatus1), it magically works!

3rd example (Setting the selected here):

@Html.DropDownList("DeliveryStatus1", new SelectListItem[] {
        new SelectListItem { 
            Selected = false, 
            Text = "Active Delivery", 
            Value = "1" },
        new SelectListItem { 
            Selected = true, 
            Text = "Deactive Delivery", 
            Value = "2" }}) //Notice that I manually set the 2nd true

But when I do that and set as DeliveryStatus1, I cannot post the data to the Controller.

What is wrong with this or what am I doing wrong? I need both to be able to SET THE SELECTED data and POST it back


Solution

  • Thanks to Stephen Muecke, for enums I gave the value as Enum.ToString() instead of the Integer value.:

    @Html.DropDownListFor(model => model.DeliveryStatus, new SelectListItem[] {
            new SelectListItem { 
                Selected = false, 
                Text = "Active Delivery", 
                Value = "Active" },
            new SelectListItem { 
                Selected = true, 
                Text = "Deactive Delivery", 
                Value = "Deactive" }})