1. The drop-down menu list item is known: Enter the code in the Controller class
1 public class Democontroller:controller
2 {
3 public ActionResult Binddropdownlist ()
4 {
5 list<selectlistitem> select1 = new list<selectlistitem>
6 {
7 new SelectListItem {Text = ' content ', value = ' value '},
8 New SelectListItem
9};
10
One viewdata["select1"] = new SelectList (Select1, "value", "Text", "Here is the value of the default item");
12
return View ();
14}
15}Use in View
1 <%= html.dropdownlist ("Select1")%>This method is simple and convenient, and can be used if the data is not read from the database.
2. Iterating through a drop-down list item from a database or array
The database connection code is omitted here, and the data that is read from the database is similar to the data stored in the string array, as the following is an example of an array. Enter the code in the Controller class
1 public class Democontroller:controller
2 {
3 public ActionResult Binddropdownlist ()
4 {
5 string[] Texts = new string[] {"One", "two", "three", n};
6 string[] values = new string[] {"1", "2", "3", n};
7
8 list<selectlistitem> Select1 = new list<selectlistitem> ();
9
Ten for (int i = 0; i < texts. Length; i++)
11 {
Select1. ADD (New SelectListItem
13 {
Text = Texts[i],
[Value = Values[i]
16});
17};
18
viewdata["Select1"] = new SelectList (Select1, "value", "Text", "Here is the value of the default item");
20
return View ();
22}
23}Use in View
1 <%= html.dropdownlist ("Select1")%>In fact, this method looks similar to the 1th kind, just when reading the data, the use of a circular statement.
3. Read all drop-down menu list items for a table from the database
Assuming that a category class already exists, you can get all the categories of the table by using the Category.getlist () method, which contains the ID and Name two data columns. Enter the code in the Controller class
1 public class Democontroller:controller
2 {
3 public ActionResult Binddropdownlist ()
4 {
5 list<categoryentiry> categories = Category.getall ();
6
7 viewdata["Categories"] = new SelectList (Categories, "ID", "Name");
8
9 return View ();
10}
One} Use in View
1//First convert data in ViewData to SelectList
2 <% selectlist categories = viewdata["Categories"] as selectlist; %>
3
4//Then output
5 <%= html.dropdownlist ("Category", categories)%>
It is important to note that there is a slight difference between the 3rd and the first 2 methods used in View, of course, the first 2 methods can be changed to the 3rd method, or the 3rd method is changed to the first 2 methods.
"NET Pick" c#.net How to dynamically bind a pull menu in MVC