脚本宝典收集整理的这篇文章主要介绍了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
[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 <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是bootstrap的样式,js添加:$('.select2').select2();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本宝典。
以上是脚本宝典为你收集整理的MVC5下拉框绑定的方法(单选)全部内容,希望文章能够帮你解决MVC5下拉框绑定的方法(单选)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。