asp.net-mvc ASP .NET MVC - 使用枚举作为模型的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4890983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP .NET MVC - Using a enum as part of the model
提问by John M
(just learning MVC)
(刚学MVC)
I have created a model class:
我创建了一个模型类:
public class Employee
{
public int ID { get; set; }
[Required(ErrorMessage="TM Number is Required")]
public string tm_number { get; set; }
//use enum?
public tmRank tm_rank { get; set; }
}
The model class refers to the enum 'tmRank':
模型类指的是枚举“tmRank”:
public enum tmRank
{
Hourly, Salary
}
When I create a view from this model the 'tm_rank' field does not appear? My hope was that MVC would create a list of the enum values.
当我从这个模型创建一个视图时,'tm_rank' 字段没有出现?我希望 MVC 会创建一个枚举值列表。
回答by mfanto
My guess is it doesn't understand what type of field to create for an Enum. An Enum can be bound to a dropdown list, a set of radio buttons, a text box, etc.
我的猜测是它不了解为 Enum 创建什么类型的字段。枚举可以绑定到下拉列表、一组单选按钮、文本框等。
What type of entry do you want for your Enum? Should they select it from a list? Answering that can help us with the code needed for that situation.
您希望 Enum 使用哪种类型的条目?他们应该从列表中选择它吗?回答这个问题可以帮助我们处理这种情况所需的代码。
Edited to add code per your comment:
编辑以根据您的评论添加代码:
public static SelectList GetRankSelectList()
{
var enumValues = Enum.GetValues(typeof(TmRank)).Cast<TmRank>().Select(e => new { Value = e.ToString(), Text = e.ToString() }).ToList();
return new SelectList(enumValues, "Value", "Text", "");
}
Then in your model:
然后在你的模型中:
public class Employee
{
public Employee()
{
TmRankList = GetRankSelectList();
}
public SelectList TmRankList { get; set; }
public TmRank TmRank { get; set; }
}
And finally you can use it in your View with:
最后,您可以在您的视图中使用它:
<%= Html.DropDownListFor(c => c.TmRank, Model.TmRankList) %>
This will hold the enum values in TmRankList. When your form is posted, TmRank will hold the selected value.
这将保存 TmRankList 中的枚举值。当您的表单发布时,TmRank 将保留所选值。
I wrote this without visual studio though, so there might be issues. But this is the general approach that I use to solve it.
我在没有visual studio的情况下写了这个,所以可能会有问题。但这是我用来解决它的一般方法。