Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding an mvc dropdown list to a basic list

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.

like image 349
Diver Dan Avatar asked Aug 05 '26 07:08

Diver Dan


1 Answers

You need to change the select list as below:

var list = new SelectList(new[]
                                      {
                                          new{ID="0",Name="- Please Select -"},
                                          new{ID="True",Name="Yes"},
                                          new{ID="False",Name="No"},
                                      }, "ID", "Name", "0");

notice the "0" in the constructor of the SelectList is string and wrapped with double quotes.

like image 118
Amir Rezvani Avatar answered Aug 06 '26 20:08

Amir Rezvani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!