public static HtmlString DropDownEnumFor <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, SelectListItem defauItem = null, object htmlAttributes = null) { var typeOfProperty = expression.ReturnType; if (!typeOfProperty.IsEnum) { throw new ArgumentException(string.Format("Type {0} is not an enum", typeOfProperty)); } //getting the enum that is defined.. int?value = (int)ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model; // if (Enum.IsDefined(typeOfProperty, expression)) // { // defaultValue = (int)ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model; // } var enumValues = new List <SelectListItem>(); if (defauItem != null) //adding the default value before anything else... { if (value == null) { defauItem.Selected = true; } enumValues.Add(defauItem); } //retrieves the elements.. enumValues.AddRange(Enum.GetValues(typeOfProperty).Cast <Enum>().Select(x => new SelectListItem() { Value = (Convert.ToInt32(x)).ToString(), Text = GeneralHelper.GetEnumDescriptionIrName(x), Selected = ((int)value) == (Convert.ToInt32(x)) })); // var selecteItem = defaultValue != null // ? enumValues.FirstOrDefault(x => Convert.ToInt32(x.Value) == defaultValue) // : enumValues.First(); return(helper.DropDownListFor(expression, enumValues, htmlAttributes: htmlAttributes)); }
public IList<SelectListItem> SelectListItemGenerator<T>(bool descriptorAsText = true, bool intAsValue = true) where T : struct, IConvertible { if (!typeof (T).IsEnum) { throw new ArgumentException("T must be an enumerated type"); } //now doing the rest of the work... IEnumerable<Enum> listElments = Enum.GetValues(typeof (T)).Cast<Enum>(); return listElments.Select(a => new SelectListItem { Text = descriptorAsText ? _generalHelper.GetEnumDescriptionIrName(a) : a.ToString(), Value = intAsValue ? (Convert.ToInt32(a)).ToString() : a.ToString() }).ToList(); }