Reputation: 363
I am having trouble binding values to a Drop Down List.
Model
public class DummyModel
{
...
public int? OptionID { get; set; }
...
}
Line In View Causing Exception
@Html.DropDownListFor(model => model.OptionID, new SelectList(ViewBag.AvailableOptions, "ID", "Name"))
The Contents of the ViewBag
?ViewBag.AvailableOptions
Count = 4
[0]: {[3, Average Speed]}
[1]: {[4, Snails pace]}
[2]: {[1, Super Fast]}
[3]: {[2, Super Slow]}
The exception that gets generated:
System.Web.HttpException: 'DataBinding: 'System.Collections.Generic.KeyValuePair`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral,
Upvotes: 0
Views: 560
Reputation: 781
If (as mentioned in the comments / from the text of the exception), ViewBag.AvailableOptions
is a dictionary you'll want to change the Id and Value properties of your select list like so :
new SelectList(ViewBag.AvailableOptions, "Key", "Value")
Since a dictionary is basically a list of KeyValuePair
objects when enumerated, its properties are (as one could imagine) Key
and Value
.
Upvotes: 1