如何将自定义对象添加到 DropDownList 项目?
我在 WebApplication 中使用 DropDownList。我需要为列表中的每个项目保留额外的信息。我怎样才能实现这个目标?
I'm using DropDownList within my WebApplication. I need to keep additional piece of information with each Item on list. How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 HTML 中,下拉菜单由
< 表示。 select>
元素,它是的集合。每个
选项
都有一个值和文本。就这样。因此,请将附加信息保留在数据存储中,并在需要时使用所选元素的值进行查询。In HTML a drop down is represented by the
<select>
element which is a collection of<option>
. Eachoption
has a value and text. That's all. So keep the additional information in your data store and use the value of the selected element to query it when needed.如何在每个列表项上使用您自己的自定义属性,例如:
以下是有关自定义属性如何验证是否存在问题的链接:
HTML 5 data- Attributes
我还应该补充一点,我包含的链接讨论了“data=”属性如何在 HTML 5 中是有效的 XHTML,但没有理由我现在可以考虑不要使用它们。您可以使用 javascript 在客户端访问它们,也可以使用
.SelectedItem
上的.Attributes()
集合在 .NET 服务器端代码中访问它们How about using your own custom attributes on each of the list items, for example:
Here's a link on how custom attributes will also validate if that is a concern:
HTML 5 data- Attributes
I should also add that the link I included talks about how "data=" attributes are valid XHTML in HTML 5 but there's no reason I can think of to not use them now. You can access them client side using javascript or in .NET server side code using the
.Attributes()
collection on the.SelectedItem
创建一个自定义 DropDownList,当然继承自 DropDownList。为数据添加另一个属性。最简单的实现是让您的新属性成为您填充 ddl 的项目的集合。您可能有一个描述已有数据的类,因此请创建该类型的属性。您甚至可以在填充该集合后设置 DataTextValue 和 DataValueField,甚至不必将其挂接到 aspx 页面中。
Make a Custom DropDownList, inheriting from the DropDownList of course. Add another property for the data. The easiest implementation would be to have your new property be a collection of the items you are populating the ddl with. You probably have a class that describes the data you already have, so make the property of that type. You could even set the DataTextValue and DataValueField from this collection after it gets populated and not even have to hook that up in the aspx page.
使附加数据在客户端可用的其他选项可能是使用与下拉列表绑定到相同数据源的转发器,并让它使用附加数据呈现隐藏字段,或者呈现 JavaScript 数组。
Other options that make your additional data available client-side could be to use a repeater which is bound to the same data source as your drop down and have it render hidden fields with the additional data, or render a javascript array.