Search code examples
asp.net-mvc-5html-helperhtml.dropdownlistfor

DropDownListFor not selecting the right value on an Edit screen


I'm using a dropdown list for a form. It works and saves just fine when I create a form. But when I load it into the Edit screen, the correct option isn't being selected by default. Instead, the first option is being selected.

I put a breakpoint at the line in the View to see if the id/value for the property is right, which it is. I'm just not sure if it's the code in the View that's wrong or how I'm passing it through the controller.

I used DropDownList before and it worked okay, but for validation purposes I switched to DropDownListFor and I immediately encountered this problem.

View (Edit)

@Html.DropDownListFor(model => model.Item_ID, (SelectList)ViewBag.Item_ID, new { @class = "form-control" })

Controller

List<ItemInfo> itemIDItems = dbContext.Items.OrderBy(item => item.Item_Title).ToList<ItemInfo>();
ViewBag.Item_ID = new SelectList(itemIDItems, "Item_ID", "Item_Title", object.Item_ID);

Model (Object, generated through EF)

public int Obj_ID { get; set; }
...
public Nullable<int> Item_ID { get; set; }
...
public virtual Items Items { get; set; }

Model (Items, generated through EF)

public int Item_ID { get; set; }
public string Item_Title { get; set; }

Solution

  • You need to change the name of the ViewBag property so it does not match the name of the property your binding to. For example your GET method should be

    var model = // get your existing model
    List<ItemInfo> itemIDItems = dbContext.Items.OrderBy(item => item.Item_Title).ToList<ItemInfo>();
    ViewBag.ItemList = new SelectList(itemIDItems, "Item_ID", "Item_Title");
    return View(model);
    

    Note that the 4th parameter of the SelectList constructor is unnecessary (it's ignored by the DropDownListFor() method) because its the value of the property your binding to that determines which option is selected.

    And the view will be

    @Html.DropDownListFor(m => m.Item_ID, (SelectList)ViewBag.ItemList, new { @class = "form-control" })
    

    If the value of Item_ID matches the value of one of the options, then that option will be selected.