直接贴代码了:
更新说明:
推荐 Enums.NET 开源组件处理 C# 枚举。这里是我整理的 Demo:https://files.cnblogs.com/files/Music/Enums.NET_Demo_VeryGood.rar
public static class EnumerableExtension { /// <summary> /// 生成用于 ASP.NET Mvc 中 DropDownListFor 的 SelectListItem 可枚举的集合 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="source">集合</param> /// <param name="funText">得到下拉框的 Text 的委托</param> /// <param name="funValue">得到下拉框的 Value 的委托</param> /// <param name="selectedValue">选中的值。建议不要设置与模型状态不一致的值,比如当前提交的下拉框中的值为 1,您如果设置 2,那么还是会显示 1,因为 Mvc 默认会从当前上下文中取值</param> /// <param name="initItems">初始化项,可为 null</param> /// <returns></returns> public static IEnumerable<SelectListItem> ToDropDownListItems<T>(this IEnumerable<T> source, Func<T, string> funText, Func<T, string> funValue, string selectedValue, IDictionary<string, string> initItems = null) { if (initItems != null && initItems.Count > 0) { foreach (var item in initItems) { SelectListItem resultItem = new SelectListItem { Text = item.Key, Value = item.Value, Selected = item.Value == selectedValue }; yield return resultItem; } } if (source != null) { IEnumerator<T> sourceIterator = source.GetEnumerator(); while (sourceIterator.MoveNext()) { T entityItem = sourceIterator.Current; yield return new SelectListItem { Text = funText(entityItem), Value = funValue(entityItem), Selected = funValue(entityItem) == selectedValue }; } } } }
简单调用:
ViewBag.dropDownListForNewsType = list.ToDropDownListItems(m => m.Name, m => m.Id.ToString(), viewModel.NewsType.ToString());
复杂调用:
ViewBag.dropDownListForParentId = listCategories.ToDropDownListItems( m => m.DepthLevel <= 1 ? (m.Name) : ("|" + new string('-', m.DepthLevel * m.DepthLevel) + m.Name), m => m.Id.ToString(), viewModel.ParentId.ToString(), new Dictionary<string, string>() { { "===请选择===", "0" } } );
运行效果图:
简单调用的运行效果图:
复杂调用的运行效果图:
谢谢浏览!