Use of the Html. DropDownList () auxiliary method in the MVC view, mvcdropdownlist
We first prepare a SelectList type in the controller, and then pass it into the view through ViewBag. List. The SelectList type is provided by the HTML auxiliary methods related to the ASP. net mvc Special List. For example, Html. DropDownList () and Html. ListBox () can all be used.
1 public ActionResult HelperDropDownList () 2 {3 List <SelectListItem> listItem = new List <SelectListItem> {4 new SelectListItem {Text = "yes", Value = "1 "}, 5 new SelectListItem {Text = "no", Value = "0"} 6}; 7 ViewBag. list = new SelectList (listItem, "Value", "Text", ""); 8 return View (); 9}
Then, you can create a drop-down list in the view.
@ Html. DropDownList ("List", ViewBag. List as SelectList, "select ")
The rendered HTML is as follows:
1 <select name = "List" id = "List"> 2 <option value = ""> select </option> 3 <option value = "1"> Yes </ option> 4 <option value = "0"> NO </option> 5 </select>
In addition, if the background data is uploaded to the view using ViewData, you can write as follows:
1 // the backend uses ViewData to transmit values to the page 2 public ActionResult HelperDropDownList () 3 {4 List <SelectListItem> listItem = new List <SelectListItem> {5 new SelectListItem {Text = "yes", Value = "1 "}, 6 new SelectListItem {Text = "no", Value = "0", Selected = true} 7}; 8 // ViewBag. list = new SelectList (listItem, "Value", "Text", ""); 9 ViewData ["List"] = new SelectList (listItem, "Value", "Text ", ""); 10 return View (); 11}
1 @ using (Html. BeginForm ("DropDownValue", "Home") 2 {
// Write the first parameter as the corresponding ViewData index. dropDownList ("List", "select") 4 <div> 5 <input type = "submit" value = "submit"/> 6 </div> 7}
Bytes --------------------------------------------------------------------------------------------------------------
How can I transfer the value selected from the drop-down list on the view page to the Controlloer method for processing? You can do this:
1 @ using (Html. beginForm ("DropDownValue", "Home") 2 {3 @ Html. dropDownList ("List", ViewBag. list as SelectList, "select") 4 <div> 5 <input type = "submit" value = "submit"/> 6 </div> 7 8}
Place the drop-down list in the form. When the form is submitted, the selected value is submitted to the Controller method.
1 public ActionResult DropDownValue(string List)2 {3 ViewBag.Result = List;4 return View();5 }
Note that the parameter name of the method that accepts the value must be consistent with the id of the html Tag.