Use Html. DropDownList to upload values, and use html. dropdownlist to upload values.
Html. DropDownList:
You can pass in a clear IEnumerable <SelectListItem>, or implicitly pass in through ViewBag or ViewData, provided that the same name is required, such as ViewBag. GenreId or ViewData ["GenreId"].
Example:
Public ActionResult Index () {var SelectItems = new List <dynamic> () {new {id = 1, name = ""}, new {id = 2, name = "Xiao Ming"}, new {id = 3, name = "" }}; // SelectList: Use the SelectList helper class to build ViewBag. selectItem = new SelectList (SelectItems, "id", "name", 2 ); // use the SelectListItem object set var SexItems = new List <SelectListItem> {new SelectListItem {Text = "male", Value = "1", Selected = true }, new SelectListItem {Text = "", Value = "0" }}; return View (SexItems );}
View:
@ Model IEnumerable <System. web. mvc. selectListItem> // use ViewBag or ViewDate to implicitly pass in, through @ Html. the name specified by DropDownList matches the attribute value of ViewBag or ViewDate (if no value is specified, the second parameter is used to search for attributes with the same name based on the specified name) @ Html. label ("person_id", "Personnel"): @ Html. dropDownList ("SelectItem", null, new {id = "person_id"}) <br/> // You can also set ViewBag. selectItem to IEnumerable <SelectListItem> @ Html. label ("person_id", "Personnel"): @ Html. dropDownList ("SelectItem", ViewBag. selectItem as IEnumerable <SelectListItem>, new {id = "person_id"}) <br/> // fill the select statement with a strongly typed view object. You need to declare the Model type @ Html. label ("sex", "gender"): @ Html. dropDownList ("sex", Model, new {id = "sex "})
Note:
1. @ the first parameter of Html. Label indicates the value of the for feature, and the second parameter indicates the lable text
2. SelectList is a further encapsulation of IEnumerable <SelectListItem>. Which one can be used based on different scenarios?
3. Converting SelectList to IEnumerable <SelectListItem> will lose the default item
Execution result:
Generated code:
<Label for = "person_id"> personnel </label>: <select id = "person_id" name = "SelectItem"> <option value = "1"> Liu Xin </option> <option selected = "selected" value = "2"> James </option> <option value = "3"> egg </option> </select> <br/> <label for = "person_id"> personnel </label>: <select id = "person_id" name = "SelectItem"> <option value = "1"> Liu Xin </option> <option value = "2"> Xiao Ming </option> <option value = "3"> egg </option> </select> <br/> <label for = "sex"> gender </label>: <select id = "sex" name = "sex"> <option selected = "selected" value = "1"> male </option> <option value = "0"> female </option> </select>