ASP .NET MVC - 使用枚举作为模型的一部分
(刚刚学习 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”:
public enum tmRank
{
Hourly, Salary
}
当我从此模型创建视图时,“tm_rank”字段不会出现?我希望 MVC 能够创建一个枚举值列表。
(just learning 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':
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是它不理解为枚举创建什么类型的字段。枚举可以绑定到下拉列表、一组单选按钮、文本框等。
您希望枚举具有什么类型的条目?他们应该从列表中选择它吗?回答这个问题可以帮助我们获得该情况所需的代码。
编辑以根据您的评论添加代码:
然后在您的模型中:
最后您可以在视图中使用它:
这将保存 TmRankList 中的枚举值。当您的表单发布时,TmRank 将保留所选值。
我在没有 Visual Studio 的情况下写了这篇文章,所以可能会有问题。但这是我用来解决这个问题的一般方法。
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.
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.
Edited to add code per your comment:
Then in your model:
And finally you can use it in your View with:
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.