Web 框架下拉框的最佳实践(ASP.NET MVC / ROR / 任何东西)
我正在尝试制定一种最佳实践,为需要绑定到数据库中的值的值构建下拉框。
目前我即将使用此列表中的第三个答案 如何在 ASP.NET MVC 中从枚举创建下拉列表?
但后来我在想,如果我强烈绑定到枚举,然后想要更改项目的顺序,或者添加新的项目,我需要确保枚举的顺序实际上不是存储在数据库中的值,并且必须具有某种类型的绑定层。
有没有人有明确的方法来处理与数据库相关的下拉列表?
I'm trying to work out a best practice for building drop down boxes for values that need to bind to values in a database.
Currently I am about to use the 3rd answer from this list How do you create a dropdownlist from an enum in ASP.NET MVC?
But then I was thinking if I bind strongly against the Enum, and then want to change the order of the items, or add new items, I'll need to make sure the order of the enum isn't actually the value being stored in the db, and have to have a binding layer of some kind.
Does anyone have the definitive way to work with drop down lists that relate to a db?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就我个人而言,我避免在视图模型中使用枚举。它们不能很好地与 ASP.NET MVC 配合使用。因此,如果我需要在其中一个视图中呈现下拉列表,我会在相应的视图模型上定义 2 个属性:
这些属性从数据库和视图中填充到我的控制器操作中:
Personally I avoid using enums in my view models. They don't play well with ASP.NET MVC. So if I need to render a dropdown list in one of my views I define 2 properties on my corresponding view model:
that are populated in my controller action from the database and in the view:
为列表提供一个强类型视图模型,并与部分视图相匹配。在控制器中执行一个操作,填充视图模型,然后将其返回到视图。无论您想在何处使用下拉列表,请将部分视图插入您的视图中。
Have a strongly typed view model for the list with a partial view to match. Have an action in a controller which fills the view model and then returns it to the view. Wherever you want to use the dropdown, insert the partial view in your view.
我喜欢使用扩展方法来完成此任务:
在控制器中,您可以选择不想在下拉列表中表示为项目的数据。请注意,在本示例中,我从数据库中选择城市:
以及视图中的实际下拉列表:
I'm a fan of using an extension method for this task:
Within your controller you select the data that you wan't to represent as items within a drop down. Note, in this example I'm selecting cities from the db:
And the actual drop down within the view: