Binding method of mvc5 dropdown box (single choice)

Time:2021-7-18

This example for you to share the mvc5 dropdown box radio binding specific code, for your reference, the specific content is as follows

1.Model

[display (name = education level)]
 public ICollection<System.Web.Mvc.SelectListItem> asdflist{ get;  set; }  // The type of drop-down box

[display (name = education level)]
[Required]
public int asdf { get;  set; }    // The attribute of this field

2.controller

(1) First write a program binding, which can be done through database binding or direct binding

[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 written help class, which is convenient for database operation
     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 =, 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 education")]
[UIExceptionResult]
 public ActionResult Edu()
{
    var edu= new EduModel();
    edu.asdflist=bind_ Education();  // Initializes the value of the drop-down box
    return View(edu);
 }

3. View


@model RsJob.Web.Models.EduModel  
<div>
    @Html.LabelFor(m => m.agj03, new { @class = "col-sm-2 control-label" })
        <div>
          @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 a bootstrap style. JS adds $(‘. Select2’). Select2();

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.