1

I have s simple dropdown which is rendered with:

@Html.DropDownListFor(m => m.Request.Value, new SelectList(items, "Value", "Text", selectedElement), new {})

where Model.Request.Value is of type int and has the value set to -1. items is build like:

var items = new List<SelectListItem<int>>();

items.Add(new SelectListItem<int>{Text = "10", Value = 10});
items.Add(new SelectListItem<int>{Text = "25", Value = 25});
items.Add(new SelectListItem<int>{Text = "100", Value = 100});
items.Add(new SelectListItem<int>{Text = "All", Value = -1});

The value of selectedElementis 25, which is of type int. However, it always renders the select with All selected, which means value = -1.

Why? And why is there a value selectedElement which get's overridden no matter what?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
KingKerosin
  • 3,639
  • 4
  • 38
  • 77

2 Answers2

0

DropDownListFor uses the value of lambda expression to select the item in the dropdown list rather than the last argument of the SelectList constructor.

I believe that the following link includes sample code that should be able to help you:

MVC DropDownList SelectedValue not displaying correctly

Community
  • 1
  • 1
Stuart
  • 754
  • 11
  • 25
0

Your strongly binding to a property in your model, so its the value of the property that determines what is selected. That's how model binding works. If you want "All" to be selected, set the value of Request.Value = -1

The 4th parameter of the SelectList constructor is ignored when binding to a property. The only time it is respected is if you were to use something like @Html.DropDownList("NotAPropertyOfMyModel, new (SelectList(...

Side note: items is IEnumerable<SelectListItem> (which is what the DropDownListFor() method requires) so creating a new IEnumerable<SelectListItem> (which is what SelectList is) is just pointless extra overhead. Your view should be just

@Html.DropDownListFor(m => m.Request.Value, items)