从数据库条目创建 DropDownList,然后在表单提交中绑定它
我在数据库表中存储了枚举条目,其中仅包含以下字段:ID
和 Name
。我想在表单上的 DropDownList 内显示存储在该表中的值。然后,用户选择一个值并提交表单。
我 找到了一种从枚举轻松创建 DropDownList 的方法(尽管最好只使用表中所有记录的 Name 字段填充 DropDownList)。但是,我还没有找到一种方法可以稍后将表单提交中的 DropDownList 绑定到一个整数值,以便与其他表单值一起放入数据库(FK - PK)。
您能否提供一些示例代码来说明如何进行此类绑定?
更新:感谢您的精彩回答。我还有一个问题:是否可以通过 AJAX 获取 DropDownList 内容,并将其放入 ViewModel 中的 DropDownList 和 SelectList 中(同时包含 ID 和 Name 参数)?我想根据用户的输入有选择地获取内容,并且我希望 ViewModel 然后填充所获取的数据。
I have entries for an enumeration stored inside a database table with only the following fields: ID
and Name
. I want to show the values stored inside this table inside a DropDownList on a form. The user then chooses a value and submits the form.
I found a way to easily create a DropDownList from an enumeration (although it would probably be best to just populate the DropDownList with the Name fields of all the records in the table). However, I haven't found a way to later bind the DropDownList in the form submission to an integer value to put into the database (FK - PK) with the other form values.
Can you provide some sample code that illustrates how to do such binding?
UPDATE: Thanks for the awesome answer. I have one more question: is it possible to fetch DropDownList content via AJAX and have it be put into the DropDownList and into the SelectList in the ViewModel (with both the ID and Name parameters)? I want to selectively fetch content based on an input the user makes and I want the ViewModel to then be filled with that fetched data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一如既往,首先定义模型:
然后是控制器:
最后是强类型视图:
As always start by defining a model:
Then the controller:
and finally the strongly typed view: