MVC5下拉框單選綁定的具體代碼實現

來源:互聯網
上載者:User
這篇文章主要為大家詳細介紹了MVC5下拉框綁定,具有一定的參考價值,感興趣的小夥伴們可以參考一下

本文執行個體為大家分享了MVC5下拉框單選綁定的具體代碼,供大家參考,具體內容如下

1.Model


[Display(Name = "學曆")] public ICollection<System.Web.Mvc.SelectListItem> asdflist{ get; set; }  //下拉框的類型[Display(Name = "學曆")][Required]public int asdf { get; set; }    //學曆這個欄位的屬性

2.controller

(1)先寫一個程式綁定,可以通過資料庫綁定或者直接綁定


[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是已經寫好的協助類,便於資料庫的操作     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)初始化,並傳給視圖


[Description("我的學曆")][UIExceptionResult] public ActionResult Edu(){    var edu= new EduModel();    edu.asdflist=bind_Education();  //初始化下拉框的值    return View(edu); }

3.視圖


@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是bootstrap的樣式,js添加:$('.select2').select2();

相關關鍵詞:
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.