C#MVC:DropDownList将枚举绑定到整型模型字段 [英] C# MVC: DropDownListFor bind a enum to a integer model-field
问题描述
我尝试了一些扩展方法,但是没有做好工作,导致所有方法需要将模型字段作为给定的枚举类型...
这是我的来源(模型和枚举):
型号:
public class Einheit
{
public Einheit()
{
Id = Guid.NewGuid();
}
public Guid Id {get;组; }
public short TypeOfSomething {get;组; }
public long Verwendungszweck {get;组;
}
枚举:
public enum Einheitsart
{
Type1 = 0,
Type2 = 1,
Type3 = 2,
Type4 = 3 ,
Type5 = 4,
Type6 = 5
}
我想要使值从0-6(为了能够保存Integer在我的模型),但是DropDownList应该显示文本Type1到Type6...
我的问题是将枚举转换为工作的SelectList。
谢谢!
您可以枚举所有枚举值,并为每个枚举值创建SelectListItems。这应该工作:
var selectList = new List< SelectListItem>();
foreach(Einheitsart art in Enum.GetValues(typeof(Einheitsart)))
{
selectList.Add(new SelectListItem(){Value =(int)art,Text = art.ToString )})
}
How can I bind an enum to a model-field of the type integer?
I tried some extension methods, but they didnt do a good job, cause all method required the model field to be the given enum-type...
Here is my source (Model and Enum):
Model:
public class Einheit
{
public Einheit()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public short TypeOfSomething { get; set; }
public long Verwendungszweck { get; set; }
}
Enum:
public enum Einheitsart
{
Type1 = 0,
Type2 = 1,
Type3 = 2,
Type4 = 3,
Type5 = 4,
Type6 = 5
}
I want to have the Values going from 0-6 (To be able to save the Integer in my Model), but the DropDownList should show the Text "Type1" to "Type6"...
The problem I have is converting the enum to a working SelectList.
Thank you!
You can enumerate over all enum values and create SelectListItems for each of them. This should work:
var selectList = new List<SelectListItem>();
foreach(Einheitsart art in Enum.GetValues(typeof(Einheitsart)))
{
selectList.Add(new SelectListItem() { Value = (int)art, Text = art.ToString() })
}
这篇关于C#MVC:DropDownList将枚举绑定到整型模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!