我正在尝试使用Html.DropDownList扩展方法,但不知道如何将其与枚举一起使用。
假设我有一个如下所示的枚举:
public enum ItemTypes
{
Movie = 1,
Game = 2,
Book = 3
}如何使用Html.DropDownList扩展方法创建包含这些值的dropdown?
或者,我最好的办法就是简单地创建一个for循环,然后手动创建Html元素?
发布于 2009-03-29 09:11:17
对于MVCV5.1,使用Html.EnumDropDownListFor
@Html.EnumDropDownListFor(
x => x.YourEnumField,
"Select My Type",
new { @class = "form-control" })对于MVC v5,使用EnumHelper
@Html.DropDownList("MyType",
EnumHelper.GetSelectList(typeof(MyType)) ,
"Select My Type",
new { @class = "form-control" })对于MVC 5和更低版本
我把Rune的答案放到了一个扩展方法中:
namespace MyApp.Common
{
public static class MyExtensions{
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
where TEnum : struct, IComparable, IFormattable, IConvertible
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new { Id = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name", enumObj);
}
}
}这允许您编写以下代码:
ViewData["taskStatus"] = task.Status.ToSelectList();作者:using MyApp.Common
发布于 2011-03-10 11:27:31
我知道我来晚了,但我想您可能会发现这个变体很有用,因为这个变体还允许您在下拉列表中使用描述性字符串而不是枚举常量。为此,使用System.ComponentModel.Description属性修饰每个枚举项。
例如:
public enum TestEnum
{
[Description("Full test")]
FullTest,
[Description("Incomplete or partial test")]
PartialTest,
[Description("No test performed")]
None
}下面是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;
...
private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
{
Type realModelType = modelMetadata.ModelType;
Type underlyingType = Nullable.GetUnderlyingType(realModelType);
if (underlyingType != null)
{
realModelType = underlyingType;
}
return realModelType;
}
private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };
public static string GetEnumDescription<TEnum>(TEnum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if ((attributes != null) && (attributes.Length > 0))
return attributes[0].Description;
else
return value.ToString();
}
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
return EnumDropDownListFor(htmlHelper, expression, null);
}
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumType = GetNonNullableModelType(metadata);
IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();
IEnumerable<SelectListItem> items = from value in values
select new SelectListItem
{
Text = GetEnumDescription(value),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
};
// If the enum is nullable, add an 'empty' item to the collection
if (metadata.IsNullableValueType)
items = SingleEmptyItem.Concat(items);
return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}然后,您可以在视图中执行此操作:
@Html.EnumDropDownListFor(model => model.MyEnumProperty)希望这对你有帮助!
**2014年1月23日编辑:微软刚刚发布了MVC5.1,现在有了EnumDropDownListFor功能。遗憾的是,它似乎并没有考虑到Description属性,所以上面的代码仍然是stands.See Enum section in微软的MVC5.1的发行说明。
更新:它确实支持 attribute [Display(Name = "Sample")] ,所以可以使用它。
[更新-刚刚注意到这一点,这里的代码看起来像是代码的扩展版本:https://blogs.msdn.microsoft.com/stuartleeks/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums/,增加了几个。如果是这样的话,归属似乎是公平的;-)]
发布于 2014-03-10 16:35:02
在中,他们添加了EnumDropDownListFor()助手,因此不需要自定义扩展:
模型
public enum MyEnum
{
[Display(Name = "First Value - desc..")]
FirstValue,
[Display(Name = "Second Value - desc...")]
SecondValue
}视图
@Html.EnumDropDownListFor(model => model.MyEnum)使用标签助手(ASP.NET MVC6)
<select asp-for="@Model.SelectedValue" asp-items="Html.GetEnumSelectList<MyEnum>()">https://stackoverflow.com/questions/388483
复制相似问题