Method (single choice) bound to the MVC5 drop-down box and single choice in the mvc5 drop-down box
This example shares the code of Single-choice binding in the MVC5 drop-down box for your reference. The details are as follows:
1. Model
[Display (Name = "")] public ICollection <System. web. mvc. selectListItem> asdflist {get; set;} // type of the drop-down box [Display (Name = "")] [Required] public int asdf {get; set ;} // attributes of this field
2. controller
(1) first write a program binding, which can be bound through the database or directly
[Description ("")] [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 written help class that facilitates database operations such as var factorOptions = dt. asEnumerable (). select (row => new SelectListItem {Text = row ["name"], Value = row ["id"]}). toList (); return factorOptions;} [Description ("")] [LoginAllowView] private List <SelectListItem> bind_Education () {List <SelectListItem> listItem = new List <SelectListItem> (); listItem. add (new SelectListItem {Text = "", Value = "1"}); listItem. add (new SelectListItem {Text = "", Value = "2"}); listItem. add (new SelectListItem {Text = "", Value = "3"}); return listItem ;}
(2) initialize and pass it to the view
[Description ("My degree")] [UIExceptionResult] public ActionResult Edu () {var edu = new EduModel (); edu. asdflist = bind_Education (); // initialize the value of the drop-down box return View (edu );}
3. View
@model RsJob.Web.Models.EduModel <div class="form-group"> @Html.LabelFor(m => m.agj03, new { @class = "col-sm-2 control-label" }) <div 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" }) </div> </div>
Select2 is the bootstrap style. js Add: $ ('. select2'). select2 ();
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.