如何将枚举绑定到整数类型的模型字段?
我尝试了一些扩展方法,但是它们并没有做得很好,因为所有方法都需要模型字段为给定的枚举类型...
这是我的来源(模特和枚举):
型号:
public class Einheit
{
public Einheit()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public short TypeOfSomething { get; set; }
public long Verwendungszweck { get; set; }
}
枚举:
public enum Einheitsart
{
Type1 = 0,
Type2 = 1,
Type3 = 2,
Type4 = 3,
Type5 = 4,
Type6 = 5
}
我希望值从0到6(为了能够在我的模型中保存整数),但是DropDownList应该将文本“Type1”显示为“Type6”......
我遇到的问题是将枚举转换为有效的SelectList。
谢谢!
答案 0 :(得分:1)
尝试我创建的以下帮助程序。
我的博客上可以看到完整的详细信息:
http://www.ninjanye.co.uk/2012/01/creating-dropdown-list-from-enum-in.html
http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23
public static class EnumHelper
{
//Creates a SelectList for a nullable enum value
public static SelectList SelectListFor<T>(T? selected)
where T : struct
{
return selected == null ? SelectListFor<T>()
: SelectListFor(selected.Value);
}
//Creates a SelectList for an enum type
public static SelectList SelectListFor<T>() where T : struct
{
Type t = typeof (T);
if (t.IsEnum)
{
var values = Enum.GetValues(typeof(T)).Cast<enum>()
.Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });
return new SelectList(values, "Id", "Name");
}
return null;
}
//Creates a SelectList for an enum value
public static SelectList SelectListFor<T>(T selected) where T : struct
{
Type t = typeof(T);
if (t.IsEnum)
{
var values = Enum.GetValues(t).Cast<Enum>()
.Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });
return new SelectList(values, "Id", "Name", Convert.ToInt32(selected));
}
return null;
}
// Get the value of the description attribute if the
// enum has one, otherwise use the value.
public static string GetDescription<TEnum>(this TEnum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
}
return value.ToString();
}
}
要使用它,只需使用以下代码:
//If you don't have an enum value use the type
ViewBag.DropDownList = EnumHelper.SelectListFor<MyEnum>();
//If you do have an enum value use the value (the value will be marked as selected)
ViewBag.DropDownList = EnumHelper.SelectListFor(myEnumValue);
注意:通过在枚举中添加description属性,它将使用它作为下拉列表的显示文本:
public enum Einheitsart
{
Type1 = 0,
[Description("2nd Type")]
Type2 = 1,
Type3 = 2,
Type4 = 3,
Type5 = 4,
Type6 = 5
}
答案 1 :(得分:0)
您可以枚举所有枚举值并为每个枚举值创建SelectListItems。这应该有效:
var selectList = new List<SelectListItem>();
foreach(Einheitsart art in Enum.GetValues(typeof(Einheitsart)))
{
selectList.Add(new SelectListItem() { Value = (int)art, Text = art.ToString() })
}