[英]How do I get an enum value from my ASP.NET MVC property?
In my ViewModel, I have a property that creates an enumeration for my form's drop down menu. 在我的ViewModel中,我有一个属性,可以为我的表单的下拉菜单创建一个枚举。
public enum Colors
{
[Description("Dark Red")]
DarkRed = 0,
[Description("Orange")]
Orange = 1,
[Description("Blue")]
Blue = 2
}
My Helper returns: 我的助手回归:
<select id="ddlColor">
<option value="DarkRed">Dark Red</option>
<option value="Orange">Orange</option>
<option value="Blue">Blue</option>
</select>
However, when I call the property in my model, I only get the name and not the value, eg DarkRed and not 0 . 但是,当我在模型中调用属性时,我只获取名称而不是值,例如DarkRed而不是0 。
model.Selections = InsertForm(model.Color);
How can I cast this in my model reference so I get the value from the enum? 如何在我的模型引用中转换它,以便从枚举中获取值 ?
You may have to cast the value like this:- 您可能必须像这样抛出值: -
var value = (int)model.Color;
NOTE:- 注意:-
All enumeration type have an underlying type, which can be any integral type except char. 所有枚举类型都有一个基础类型,除了char之外,它可以是任何整数类型。
You could easily cast it to an int
. 您可以轻松地将其转换为int
。
By default enums are Int32
. 默认情况下,枚举是Int32
。
so you could say 所以你可以说
var value = (int)model.Color;
Since you are using asp.net mvc, i'm going to assume that model.Selections is a List<SelectListItem>
. 由于您使用的是asp.net mvc,我将假设model.Selections是List<SelectListItem>
。
See below. 见下文。
public List<SelectListItem> GetList<TEnum>() where TEnum : struct
{
var items = new List<SelectListItem>();
foreach (int value in Enum.GetValues(typeof(TEnum)))
{
items.Add(new SelectListItem
{
Text = Enum.GetName(typeof(TEnum), value),
Value = value
});
}
return items;
}
You can now say model.Selections = GetList<Color>();
你现在可以说model.Selections = GetList<Color>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.