常规列表绑定到下拉列表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常规列表绑定到下拉列表相关的知识,希望对你有一定的参考价值。

  1. /// <summary>
  2. /// Converts an IEnumberable to a list of SelectListItems
  3. /// </summary>
  4. /// <typeparam name="T">Type of items in data</typeparam>
  5.  
  6. /// <typeparam name="TValueType">Type of property to be used for the Value property</typeparam>
  7. /// <typeparam name="TTextType">Type of property to be used for the Textproperty</typeparam>
  8. /// <param name="data">List to convert</param>
  9. /// <param name="defaultItem">An optional extra listItem appeneded at the beginning of the list</param>
  10. /// <param name="valueProperty">property of T to be used for the Value property</param>
  11. /// <param name="textProperty">property of T to be used for the Text property</param>
  12. /// <param name="selectedValue">Item in return value that should be selected</param>
  13. /// <returns></returns>
  14. 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)
  15. {
  16. var list = new List<SelectListItem>();
  17.  
  18. if (defaultItem != null)
  19. {
  20. list.Add(defaultItem);
  21. }
  22. if (data == null)
  23. return list;
  24.  
  25. var memberInfo = textProperty.Body as MemberExpression;
  26. var textPropName = memberInfo.Member.Name;
  27.  
  28. var valmemberInfo = valueProperty.Body as MemberExpression;
  29. var valuePropName = valmemberInfo.Member.Name;
  30.  
  31.  
  32. Type t = typeof(T);
  33.  
  34. var textProp = t.GetProperties().Where(prop => prop.Name == textPropName).Single();
  35. var valueProp = t.GetProperties().Where(prop => prop.Name == valuePropName).Single();
  36.  
  37. foreach (var item in data)
  38. {
  39.  
  40. var text = textProp.GetValue(item, null);
  41. var value = valueProp.GetValue(item, null);
  42.  
  43. list.Add(new SelectListItem()
  44. {
  45. Text = text.ToString(),
  46. Value = value.ToString(),
  47. Selected = (selectedValue == value.ToString())
  48. }
  49. );
  50. }
  51.  
  52. return list;
  53. }

以上是关于常规列表绑定到下拉列表的主要内容,如果未能解决你的问题,请参考以下文章

如何将值绑定到角度下拉列表以编辑某些数据

使用 Angular JS 在下拉列表中绑定 MVC 枚举列表

如何将 Firestore 文档列表绑定到 Flutter 中的下拉菜单?

Angular 6 无法从提供的对象中自动选择/绑定下拉列表值

在WPF中怎么将ComboBox的下拉列表的数据进行绑定?还有能不能TXT文件中的列表?

将文本框、日期和下拉列表值绑定到参数 angularJS wcfRest