0

I currently have a dropdownlist that looks like this

@Html.DropDownList("ItemID", null, "-- Select --", htmlAttributes: new { @class = "form-control chosen-select" })

which produces a default value of "-- Select --"

But I want to change this so the default is the current ItemID in the model.

So something like this

@Html.DropDownList("ItemID", null, @Model.ItemID, htmlAttributes: new { @class = "form-control chosen-select" })

How can I accomplish this?

2 Answers2

0

The second argument here should be entire list of values. i.e.

@Html.DropDownList("ItemID", Model.ListOfValues, Model.ItemID, htmlAttributes: new { @class = "form-control chosen-select" })

such that Model.ItemID should exist in Model.ListOfValues list

jahnavi13
  • 42
  • 4
0

The second argument, the one you've set null, should be a collection of SelectListItem objects, one of which has its Selected property set to true. In your code:

 model.ItemID = 123;

 model.Items = dbquery.Items.Select(dbitem => new SelectListItem(){ 
    Text = dbitem.DisplayName,
    Value = dbitem.ID,
    Selected = (model.ItemID == dbitem.ID)
 });

Then in your markup:

@Html.DropDownList("ItemID", @Model.Items, @Model.ItemID, htmlAttribu...
Caius Jard
  • 72,509
  • 5
  • 49
  • 80