在 ASP.NET MVC 3 中使用枚举
有没有一种聪明的方法可以让 MVC 脚手架为枚举值的模型属性呈现下拉列表或列表框?
示例:
public class MyModel
{
public Color MyColor { get; set; }
public Option Options { get; set; }
}
public enum Color
{
None = 0,
Red = 1,
Blue = 2,
White = 3
}
[Flags]
public enum Option
{
NotSet = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
对于“颜色”属性,下拉菜单会很好。对于“选项”属性,组合框或复选框列表会很酷。
MVC 框架/工具是否对此提供了任何类型的支持?目前,当我从模型创建视图时,Visual Studio 仅忽略枚举类型的模型属性。
实现这一点的最佳方法是什么?
Is there a clever way to get the MVC scaffolding to render a dropdown or listbox for model properties that are enum values?
Example:
public class MyModel
{
public Color MyColor { get; set; }
public Option Options { get; set; }
}
public enum Color
{
None = 0,
Red = 1,
Blue = 2,
White = 3
}
[Flags]
public enum Option
{
NotSet = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
For the “Color” property, a dropdown would be nice. And for the “Options” property, a combo box or list of checkboxes would be cool.
Is there any kind of support built into the MVC framework/tooling for this? Currently, Visual Studio just ignores the model properties of enum types when I create a View from the model.
What would be the best way to implement this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
帮助程序方法
枚举的下拉列表
我已经在我自己的项目中成功地利用了它。
Helper method
Dropdownlist for Enum
I've utilized this successfully in my own projects.
这里有很好的解决方案: 如何做您从 ASP.NET MVC 中的枚举创建下拉列表?
显然,这是用于下拉列表的,但对于您想要的其他 UI 选项,您可以使用值集合通过循环创建它们。
不是内置的,但很容易做到。
Great solution here: How do you create a dropdownlist from an enum in ASP.NET MVC?
That's for the drop-down, obviously, but for the other UI options you want you can use the collection of values to create them via loops.
Not built in, but pretty easy to do.