ASP .NET MVC - 使用枚举作为模型的一部分 [英] ASP .NET MVC - Using a enum as part of the model
问题描述
(刚学MVC)
我创建了一个模型类:
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; }
}
模型类是指枚举'tmRank
The model class refers to the enum 'tmRank':
public enum tmRank
{
Hourly, Salary
}
当我从这个模型中创建一个视图中的tm_rank字段不会出现?我的希望是,MVC将创造枚举值的列表。
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.
推荐答案
我的猜测是它不懂要创建什么类型的字段一个枚举。一个ENUM可以绑定到一个下拉列表,一组单选按钮,文本框等。
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.
你想为你的枚举什么类型的入口?他们应该从列表中选择呢?回答可以帮助我们需要的那种情况下,code。
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.
编辑,以每您的评论添加code:
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) %>
这将在TmRankList举行枚举值。当你的形式发布,TmRank将持有选定的值。
This will hold the enum values in TmRankList. When your form is posted, TmRank will hold the selected value.
我写了这个没有视觉工作室的,所以可能会有问题。但是,这是我用来解决这个问题的一般方法。
I wrote this without visual studio though, so there might be issues. But this is the general approach that I use to solve it.
这篇关于ASP .NET MVC - 使用枚举作为模型的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!