MVC5下拉框绑定的方法(单选)
本文实例为大家分享了MVC5下拉框单选绑定的具体代码,供大家参考,具体内容如下
1.Model
[Display(Name="学历")] publicICollectionasdflist{get;set;}//下拉框的类型 [Display(Name="学历")] [Required] publicintasdf{get;set;}//学历这个字段的属性
2.controller
(1)先写一个程式绑定,可以通过数据库绑定或者直接绑定
[Description("学历")]
[LoginAllowView]
privateListbind_Education()
{
StringBuildersb=newStringBuilder();
sb.Append("selectid,name");
sb.Append("fromEdu_file");
DataTabledt=sqlHelp.getData(sb.ToString());//sqlHelp是已经写好的帮助类,便于数据库的操作
varfactorOptions=dt.AsEnumerable().Select(row=>newSelectListItem
{
Text=row["name"],
Value=row["id"]
}).ToList();
returnfactorOptions;
}
[Description("学历")]
[LoginAllowView]
privateListbind_Education()
{
ListlistItem=newList();
listItem.Add(newSelectListItem{Text="本科",Value="1"});
listItem.Add(newSelectListItem{Text="硕士",Value="2"});
listItem.Add(newSelectListItem{Text="博士",Value="3"});
returnlistItem;
}
(2)初始化,并传给视图
[Description("我的学历")]
[UIExceptionResult]
publicActionResultEdu()
{
varedu=newEduModel();
edu.asdflist=bind_Education();//初始化下拉框的值
returnView(edu);
}
3.视图
@modelRsJob.Web.Models.EduModel@Html.LabelFor(m=>m.agj03,new{@class="col-sm-2control-label"}) @Html.DropDownListFor(model=>model.asdf,Model.asdflist,new{@class="form-controlselect2",style="width:100%;"}) @Html.ValidationMessageFor(m=>m.asdf,"",new{@class="text-danger"})
select2是bootstrap的样式,js添加:$('.select2').select2();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。