Example #1
0
        /// <param name="typeName">类名称(注意:内部类的调用方式  ContainerClassName+InternalClassName)</param>
        /// <param name="selectedValue"></param>
        /// <param name="isAllowedEmpty">是否允许空选项</param>
        /// <returns></returns>
        public static IEnumerable <SelectListItem> GenerateItemsFromStringItems(string typeName,
                                                                                string selectedValue = null, bool isAllowedEmpty = false)
        {
            var results = new List <SelectListItem>();

            var stringItems = StringItem.GetTypeItems(typeName);

            if (stringItems != null && stringItems.Length > 0)
            {
                int index = 0;
                foreach (StringItem si in stringItems)
                {
                    var value = si.Code;
                    var text  = si.Name;

                    var listItem = new SelectListItem()
                    {
                        Text  = text,
                        Value = value
                    };

                    if (!string.IsNullOrWhiteSpace(selectedValue) && value == selectedValue)//设置选中值
                    {
                        listItem.Selected = true;
                    }

                    if (string.IsNullOrWhiteSpace(selectedValue) && !isAllowedEmpty && index == 0) //如果不允许为空,则默认选中第一项
                    {
                        listItem.Selected = true;
                    }

                    results.Add(listItem);

                    index++;
                }
            }

            if (isAllowedEmpty)//是否允许空选项
            {
                results.Insert(0, new SelectListItem()
                {
                    Text = string.Empty, Value = string.Empty
                });
            }

            return(results);
        }