This article describes how to display DropDownList in a Web page.
Step 1: Add a method inside the control
Public actionresult showdropdownlist () { return View (); }
Step 2: Add code to the View section
@Html. DropDownList ("Department",NewList<selectlistitem> { NewSelectListItem {Text ="IT", Value ="1", Selected =true}, NewSelectListItem {Text ="HR", Value ="2"}, NewSelectListItem {Text ="Payroll", Value ="3"},}, "Select Department")
The above section is an option to add DropDownList as a "manual", and if you want to read the content through the database, first add the context and then get the contents of the datasheet through the context.
public ActionResult Showdropdownlist () { Sampledatacontext db = new Sampledataco ntext (); Viewbag.departments = new selectlist (db. Departments, ", " name ); return View (); }
@Html. DropDownList ("departments""select Department")
The data saved in the viewbag.departments is automatically displayed in the DropDownList.
If you want an item to be displayed when it is loaded, you can
New " DepartmentID " " Name ");
Change to:
New " DepartmentID " " Name ","1");
Here "1" refers to the ID of the display item.
But this approach is still more "stupid", we can set a property in the table called isselected (as shown in the table), the value of each option to determine which item is selected.
PublicActionResult showdropdownlist () {Sampledatacontext db=NewSampledatacontext (); List<SelectListItem> Selectlistitems =NewList<selectlistitem>(); foreach(varDepartmentinchdb. Departments) {SelectListItem SelectListItem=NewSelectListItem {Text=Department. Name, Value=Department. Departmentid.tostring (), Selected= Department. Isselected.hasvalue? Department. Isselected.value:false }; Selectlistitems.add (SelectListItem); } viewbag.departments=Selectlistitems; returnView ();}
The view side remains the same.
ASP. NET MVC Dropdownlist