This article is mainly for everyone to introduce the MVC5 drop-down box binding, with a certain reference value, interested in small partners can refer to
The example of this article for everyone to share the MVC5 drop-down box single-select binding code, for your reference, the specific content as follows
1.Model
[Display (Name = "education")] public icollection<system.web.mvc.selectlistitem> asdflist{get; set;} Type of drop-down box [Display (Name = "education")][required]public int asdf {get; set;} Education the properties of this field
2.controller
(1) First write a program binding, either through the database binding or directly bound
[Description ("Education")] [Loginallowview] Private list<selectlistitem> bind_education () { StringBuilder sb = new StringBuilder (); Sb. Append ("select Id,name"); Sb. Append ("from Edu_file"); DataTable dt = Sqlhelp.getdata (sb.) ToString ());//sqlhelp is a helper class that has been written to facilitate the operation of the database var factoroptions = dt. AsEnumerable (). Select (row = new SelectListItem { Text = row["Name"], Value = row["id"] }). ToList (); return factoroptions;} [Description ("Education")] [Loginallowview]private list<selectlistitem> bind_education () { list<selectlistitem> ListItem = new List<selectlistitem> (); Listitem.add (new SelectListItem {Text = "undergraduate", Value = "1"}); Listitem.add (new SelectListItem {Text = "master", Value = "2"}); Listitem.add (new SelectListItem {Text = "Doctor", Value = "3"}); return listItem; }
(2) Initialize and pass to view
[Description ("My Qualifications")] [Uiexceptionresult] public ActionResult Edu () { var edu= new Edumodel (); Edu.asdflist=bind_education (); Initializes the value of the drop-down box to return View (EDU);
3. View
@model RsJob.Web.Models.EduModel <p class= "Form-group" > @Html. labelfor (M = m.agj03, new {@class = " Col-sm-2 Control-label "}) <p class=" col-sm-10 "> @Html. dropdownlistfor (model = MODEL.ASDF, Model.asdflist, new {@class = "Form-control select2", style = "width:100%;"}) @Html. validationmessagefor (M = m.asdf, "", new {@class = "Text-danger"}) </p> </p>
Select2 is the bootstrap style, JS added: $ ('. Select2 '). Select2 ();