当前位置: 移动技术网 > IT编程>开发语言>.net > MVC5下拉框绑定的方法(单选)

MVC5下拉框绑定的方法(单选)

2017年12月08日  | 移动技术网IT编程  | 我要评论

人妖保险员,信阳市二高贴吧,吞噬星空快眼看书

本文实例为大家分享了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  
<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();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网