您现在的位置是:网站首页> 编程资料编程资料
MVC5下拉框绑定的方法(单选)_实用技巧_
2023-05-24
318人已围观
简介 MVC5下拉框绑定的方法(单选)_实用技巧_
本文实例为大家分享了MVC5下拉框单选绑定的具体代码,供大家参考,具体内容如下
1.Model
[Display(Name = "学历")] public ICollectionasdflist{ get; set; } //下拉框的类型 [Display(Name = "学历")] [Required] public int asdf { get; set; } //学历这个字段的属性
2.controller
(1)先写一个程式绑定,可以通过数据库绑定或者直接绑定
[Description("学历")] [LoginAllowView] private List 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 bind_Education() { List listItem = new List(); 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@Html.LabelFor(m => m.agj03, new { @class = "col-sm-2 control-label" })@Html.DropDownListFor(model => model.asdf, Model.asdflist, new { @class = "form-control select2", style = "width: 100%;" }) @Html.ValidationMessageFor(m => m.asdf, "", new { @class = "text-danger" })
select2是bootstrap的样式,js添加:$('.select2').select2();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- MVC实现下拉框联动效果(单选)_实用技巧_
- Asp.Net程序目录下文件夹或文件操作导致Session失效的解决方案_实用技巧_
- ASP.NET MVC 使用Bootstrap的方法_实用技巧_
- asp.net MVC下使用rest的方法_实用技巧_
- 微信JS-SDK分享功能的.Net实现代码_实用技巧_
- Asp.net Mvc表单验证气泡提示效果_实用技巧_
- java 单例模式(饿汉模式与懒汉模式)_实用技巧_
- ASP.NET Core Razor 页面路由详解_实用技巧_
- MVC生成页码选择器返回HTML代码详解_实用技巧_
- 详解ASP.NET Core 中的多语言支持(Localization)_实用技巧_
