0

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,

3
  • 2
    Please add the action code so that we can see what you are assigning to ViewBag.AvailableOptions Commented Apr 30, 2018 at 15:55
  • What type is in ViewBag.AvailableOptions ? Commented Apr 30, 2018 at 16:14
  • The type appears to be a Dictionary. Commented Apr 30, 2018 at 16:16

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Francis! This works the way I would expect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.