MVC5 Drop down Box Binding Method (Radio)

  • 2021-10-11 18:01:35
  • OfStack

In this article, we share the specific code of MVC5 drop-down box radio binding for your reference. The specific contents are as follows

1.Model


[Display(Name = " Educational background ")]
 public ICollection<System.Web.Mvc.SelectListItem> asdflist{ get; set; }  // Type of drop-down box 

[Display(Name = " Educational background ")]
[Required]
public int asdf { get; set; }    // Attributes of the field Education 


2.controller

(1) Write a program binding first, which can be bound by database or directly


[Description(" Educational background ")]
[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 , Facilitate the operation of database 
     var factorOptions = dt.AsEnumerable().Select(row => new SelectListItem
      {
        Text = row["name"],
        Value = row["id"]
      }).ToList();
      return factorOptions;
}

[Description(" Educational background ")]
[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's degree ", Value = "2" });
     listItem.Add(new SelectListItem { Text = " Doctor ", Value = "3" });
     return listItem;
 }

(2) Initialize and pass to the view


[Description(" My educational background ")]
[UIExceptionResult]
 public ActionResult Edu()
{
    var edu= new EduModel();
    edu.asdflist=bind_Education();  // Initialize the value of the drop-down box 
    return View(edu);
 }

3. Views


@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 style of bootstrap, and js is added: $('. select2'). select2 ();


Related articles: