I am trying to add a basic dropdown list to my view with a simple “Please Select”,”Yes”,”No” selection
By default I want “Please Select” to be selected.
I create a simple selectlist and add the 3 items to it.
var list = new SelectList(new[]
{
new{ID="0",Name="- Please Select -"},
new{ID="True",Name="Yes"},
new{ID="False",Name="No"},
},"ID","Name",0);
ViewBag.List= list;
My view
@Html.DropDownList("Terms", ViewBag.List as SelectList, new { @class = "drop"})
However every time the page is loaded ID “False” is selected.
At the controller level I can see that ID 0 is selected however somehow the view is changing the selected item to be the last item in the list.
What do I need to change?
I just test using ID 0,1,2 and it works however I would like to be able to use true false as it maps back to a bool field in my model.
You need to change the select list as below:
notice the “0” in the constructor of the SelectList is string and wrapped with double quotes.