MVC5 下拉框绑定(单选)_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > MVC5 下拉框绑定(单选)

MVC5 下拉框绑定(单选)

 2017/6/28 5:58:45  百变小樱007  程序员俱乐部  我要评论(0)
  • 摘要:1.Model[Display(Name="学历")]publicICollection<System.Web.Mvc.SelectListItem>asdflist{get;set;}//下拉框的类型[Display(Name="学历")][Required]publicintasdf{get;set;}//学历这个字段的属性2.controller(1)先写一个程式绑定,可以通过数据库绑定或者直接绑定[Description("学历"
  • 标签:MVC

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   
<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();

 

发表评论
用户名: 匿名