1 public static class HtmlHelperExt 2 { 3 public static MvcHtmlString EnumDropDownList<TEnum>(this HtmlHelper htmlHelper, string name, TEnum selectedValue) 4 { 5 IEnumerable<TEnum> values = Enum.GetValues(typeof (TEnum)) 6 .Cast<TEnum>(); 7 8 IEnumerable<SelectListItem> items = 9 from value in values 10 select new SelectListItem 11 { 12 Text = value.ToString(), 13 Value = value.ToString(), 14 Selected = (value.Equals(selectedValue)) 15 }; 16 17 return htmlHelper.DropDownList( 18 name, 19 items 20 ); 21 } 22 23 public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, 24 Expression<Func<TModel, TEnum>> expression) 25 { 26 ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); 27 IEnumerable<TEnum> values = Enum.GetValues(typeof (TEnum)).Cast<TEnum>(); 28 29 IEnumerable<SelectListItem> items = 30 values.Select(value => new SelectListItem 31 { 32 Text = value.ToString(), 33 Value = value.ToString(), 34 Selected = value.Equals(metadata.Model) 35 }); 36 37 return htmlHelper.DropDownListFor( 38 expression, 39 items 40 ); 41 } 42 }
HtmlHelper
时间: 2024-10-16 01:47:50