/ Published in: C#
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/// <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; }