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

2025-05-29 0 103

本文实例为大家分享了MVC5下拉框单选绑定的具体代码,供大家参考,具体内容如下

1.Model

?

1

2

3

4

5

6
[Display(Name = "学历")]

public ICollection<System.Web.Mvc.SelectListItem> asdflist{ get; set; } //下拉框的类型

[Display(Name = "学历")]

[Required]

public int asdf { get; set; } //学历这个字段的属性

2.controller

(1)先写一个程式绑定,可以通过数据库绑定或者直接绑定

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26
[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)初始化,并传给视图

?

1

2

3

4

5

6

7

8
[Description("我的学历")]

[UIExceptionResult]

public ActionResult Edu()

{

var edu= new EduModel();

edu.asdflist=bind_Education(); //初始化下拉框的值

return View(edu);

}

3.视图

?

1

2

3

4

5

6

7

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

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 MVC5下拉框绑定的方法(单选) https://www.kuaiidc.com/99208.html

相关文章

发表评论
暂无评论