• .net mvc下拉列表DropDownList控件绑定数据


    下拉列表 以性别为例

    --------------------------------------

    代码复制格式乱就用 ctrl+K+D

    代码没写全,如果出现波浪线请 解析—引用

    ---------------------------------------

    视图代码

    //表达式,对象的集合,一个对象-----第一个为空的值

    @Html.DropDownListFor(model => model.sex,ViewBag.sex as IEnumerable<SelectListItem>,“请选择性别”)

    @Html.DropDownListFor(model => model.sex,ViewBag.sex as SelectList,“请选择性别”)

      //要放回窗体的名称---一般为model的字段,对象的集合,一个对象--第一个为空的值

    @Html.DropDownList("sex",ViewBag.sex as IEnumerable<SelectListItem>,"请选择性别")

    @Html.DropDownList("sex",(SelectList)ViewData["sex"],"请选择性别")

    @Html.DropDownList("sex","请选择性别")

    控制器代码

    public ActionResult EditInfo(int id)
            {
                ViewBag.sex = new SelectList(EnumHelper.GetSelectList<sex>(),"Value","Text", Admins.sex);//这句可换
                return View(Admins);
            }

    数据为列表的

    List<SelectListItem> listItem = new List<SelectListItem>();

    listItem.Add(new SelectListItem { Text = "是", Value = "1" });

    listItem.Add(new SelectListItem { Text = "否", Value = "0" });

    ViewData["List"] = new SelectList(listItem, "Value", "Text", "");

    数据源为枚举的

    //参数依次为数据集合,数据值,数据文本,选中项的值--默认项

    ViewBag.sex = new SelectList(EnumHelper.GetSelectList<sex>(),"Value","Text", Admins.sex);

    ViewData["sex"]= new SelectList(EnumHelper.GetSelectList<sex>(),"Value","Text", Admins.sex);

    //参数依次为数据集合,选中项的值--默认项

      ViewBag.sex= new SelectList(Enum.GetValues(typeof(sex)), "");

    数据源为表的

      ViewBag.list = new SelectList(db.sex, "Id", "Name", ""); 

    枚举代码

    public enum sex
        {
            女 = 0,
            男 = 1,
            其他 = 2,
        }

        public enum sex
        {
            /// <summary> 
            /// 女 
            /// </summary> 
            [SelectDisplayName("女")]
            Female = 0,

            /// <summary> 
            /// 男 
            /// </summary> 
            [SelectDisplayName("男")]
            Male = 1,

            /// <summary> 
            /// 其他 
            /// </summary> 
            [SelectDisplayName("其他")]
            Other = 2
        }

    用第二种枚举想要获取中文就要用以下方法

      获取枚举注释

    namespace Common
    {

        /// <summary> 
        /// 自定义注解属性 
        /// </summary> 
        public class SelectDisplayNameAttribute : Attribute
        {
            private string _diaplayName;
            public string DisplayName
            {
                get
                {
                    return _diaplayName;
                }
            }
            public SelectDisplayNameAttribute(string displayName)
            {
                _diaplayName = displayName;
            }

        }

        public class EnumHelper
        {
            /// <summary> 
            /// 获取自定义属性获取的内容 
            /// </summary> 
            /// <param name="obj"></param> 
            /// <returns></returns> 
            private static string GetEnumDescription(Object obj)
            {

                //获取枚举对象的枚举类型 
                Type type = obj.GetType();
                //通过反射获取该枚举类型的所有属性 
                FieldInfo[] fieldInfos = type.GetFields();
                foreach (FieldInfo field in fieldInfos)
                {
                    //不是参数obj,就直接跳过 
                    if (field.Name != obj.ToString())
                    {
                        continue;
                    }
                    //取出参数obj的自定义属性 
                    if (field.IsDefined(typeof(SelectDisplayNameAttribute), true))
                    {
                        return (field.GetCustomAttributes(typeof(SelectDisplayNameAttribute), true)[0] as SelectDisplayNameAttribute).DisplayName;
                    }

                }
                return obj.ToString();
            }

            /// <summary> 
            ///  将枚举类型的值和自定义属性配对组合为 List<SelectListItem/>
            /// </summary> 
            /// <param name="enumType"></param> 
            /// <returns></returns> 
            public static List<SelectListItem> GetSelectList<T>(object defaultvalue=null)
            {
                var enumType = typeof(T);
                List<SelectListItem> selectList = new List<SelectListItem>();
                foreach (var obj in Enum.GetValues(enumType))
                {
                    // 注意一定要Value = obj.ToString()  
                    //原因是Value = (int)(obj.ToString()),这样取的枚举是对应的int值,在@Html.DropDownListFor中是无法显示默认选中值的,问题原因未解 
                    selectList.Add(new SelectListItem { Text = GetEnumDescription(obj), Value = obj.ToString() });
                }
                return selectList;
            }
            public static string GetEnumName(Object obj)
            {
                return GetEnumDescription(obj);
            }
        }
    }


    欢迎大神来订正我!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • 相关阅读:
    GWT中如何将EMF对象存储为XMI/从XMI反序列化为对象
    springboot工程启动时报JSR330 'javax.inject.Inject' annotation found and supported for autowiring ,启动缓慢甚至卡住不动
    深度剖析ArrayList和LinkedList
    IRasterGeometryProc,一个可以控制raster对象的接口
    sessionStorage的使用
    spring配置问题:严重: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
    Error parsing HTTP request header Note: further occurrences of HTTP header parsing errors...java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are
    Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if exp
    No 'AccessControlAllowOrigin' header is present之跨域问题及解决方案
    Caused by: java.lang.NoClassDefFoundError: Ljavax/servlet/http/HttpServletRequest;
  • 原文地址:https://www.cnblogs.com/miaololi/p/6669823.html
Copyright © 2020-2023  润新知