ToSelectListHelper

public static class SelectListHelper { public static SelectList ToSelectListWithAllOption<T>(this IEnumerable<T> items, Func<T, object> valueSelector, Func<T, string> descSelector) { return items.ToSelectListWithAllOption(valueSelector, descSelector, null); } private static SelectList ToSelectListWithAllOption<T>(this IEnumerable<T> items, Func<T, object> valueSelector, Func<T, string> descSelector, object selectedValue) { var enumerable = items as IList<T> ?? items.ToList(); var blankItem = (enumerable.Count() > 1) ? "ALL" : null; return enumerable.ToSelectList(valueSelector, descSelector, selectedValue, blankItem); } public static SelectList ToSelectList<T>(this IEnumerable<T> items, Func<T, object> valueSelector, Func<T, string> descSelector, object selectedValue, string blankItem) { var displayItems = new ArrayList(); var enumerable = items as IList<T> ?? items.ToList(); if (!enumerable.Any()) return (selectedValue == null) ? new SelectList(displayItems, "Value", "Text") : new SelectList(displayItems, "Value", "Text", selectedValue); if (null != blankItem) displayItems.Add(new { Value = "", Text = blankItem }); var reformatedItems = enumerable.Select(item => new { Value = (string)valueSelector(item), Text = descSelector(item) }); displayItems.AddRange(reformatedItems.ToArray()); return (selectedValue == null) ? new SelectList(displayItems, "Value", "Text") : new SelectList(displayItems, "Value", "Text", selectedValue); } }
Helper to build SelectList items in MVC

*USAGE*
Model = data.ToSelectList(x => x.Id, x => x.Description, object selectedValue, string blankItem)

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.