常规列表绑定到下拉列表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常规列表绑定到下拉列表相关的知识,希望对你有一定的参考价值。
/// <summary> /// Converts an IEnumberable to a list of SelectListItems /// </summary> /// <typeparam name="T">Type of items in data</typeparam> /// <typeparam name="TValueType">Type of property to be used for the Value property</typeparam> /// <typeparam name="TTextType">Type of property to be used for the Textproperty</typeparam> /// <param name="data">List to convert</param> /// <param name="defaultItem">An optional extra listItem appeneded at the beginning of the list</param> /// <param name="valueProperty">property of T to be used for the Value property</param> /// <param name="textProperty">property of T to be used for the Text property</param> /// <param name="selectedValue">Item in return value that should be selected</param> /// <returns></returns> public static List<SelectListItem> ToSelectList<T, TValueType, TTextType>(IEnumerable<T> data, SelectListItem defaultItem, Expression<Func<T, TValueType>> valueProperty, Expression<Func<T, TTextType>> textProperty, string selectedValue) { if (defaultItem != null) { list.Add(defaultItem); } if (data == null) return list; var memberInfo = textProperty.Body as MemberExpression; var textPropName = memberInfo.Member.Name; var valmemberInfo = valueProperty.Body as MemberExpression; var valuePropName = valmemberInfo.Member.Name; var textProp = t.GetProperties().Where(prop => prop.Name == textPropName).Single(); var valueProp = t.GetProperties().Where(prop => prop.Name == valuePropName).Single(); foreach (var item in data) { var text = textProp.GetValue(item, null); var value = valueProp.GetValue(item, null); { Text = text.ToString(), Value = value.ToString(), Selected = (selectedValue == value.ToString()) } ); } return list; }
以上是关于常规列表绑定到下拉列表的主要内容,如果未能解决你的问题,请参考以下文章
使用 Angular JS 在下拉列表中绑定 MVC 枚举列表
如何将 Firestore 文档列表绑定到 Flutter 中的下拉菜单?
Angular 6 无法从提供的对象中自动选择/绑定下拉列表值