asp.net dropdownlist - 在数据库值之前添加空行
在我的页面上,我有一个 DropDownList
,我用来自 SqlDataSource
的数据库值填充它(请参见下面的代码)。
如何在值之前添加自己的文本或空行?
<asp:DropDownList ID="drpClient" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dsClients" DataTextField="name"
DataValueField="client_id">
</asp:DropDownList>
<asp:SqlDataSource ID="dsClients" runat="server"
ConnectionString="my_connection_string"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [client_id], [name] FROM [clients]">
</asp:SqlDataSource>
谢谢。
PS 您是否建议使用 SqlDataSource
还是使用其他方式填充更好?
On my page I have a DropDownList
which I populate with database values from an SqlDataSource
(see code below).
How can I add my own text or a blank line before the values?
<asp:DropDownList ID="drpClient" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dsClients" DataTextField="name"
DataValueField="client_id">
</asp:DropDownList>
<asp:SqlDataSource ID="dsClients" runat="server"
ConnectionString="my_connection_string"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [client_id], [name] FROM [clients]">
</asp:SqlDataSource>
Thanks.
P.S. Do you recommend using a SqlDataSource
or is it better to populate another way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您只需在其中添加 ListItem 即可DropDownList 标记。 之后将附加来自数据源的所有值。
You can simply add a ListItem inside the DropDownList Markup. All the values from the DataSource will be appended after that.
它很容易被忽略,所以不要忘记我添加的
AppendDataBoundItems
属性。It's easy to miss, so don't forget the
AppendDataBoundItems
attribute I added.我还没有真正测试过这一点,但我假设您可以在绑定下拉列表后添加一个项目。 您可以将此事件添加到您想要添加此空框的任何下拉列表中。
I haven't really tested this but I'm assuming that you could add an item after you have binded the the drop down list. You could add this event to any dropdown list you'd like to add this empty box to.
我解决了更改选择命令添加一个空选项的问题:
问候!
I solve changing the select command adding an empty option:
Greetings!!!
在我的剃刀风格实现中,它看起来像这样:
在加载时执行的 javascript 中,我有这样的:
通过不引人注目的验证还有更灵活的解决方案(不依赖 HTML5):
当然,有一个服务器端也检查一下。
我认为应付课程不是一个好主意。
例如,我在页面中显示的所有内容都是某个类。 该类有几个可枚举类型属性。 复制所有这些属性,但在某些附加类中使它们可以为空,就像 stackoverflow 上的一些人建议的那样,这将是一场噩梦。
毕竟,为什么我应该为了某些特定的标记而改变我的业务逻辑呢? 相反,我通过 JavaScript 和一些模型检查来处理所有事情。
In razor-style implementation at me it looks like this:
And in javascript which is executed on load I have this:
There is also more flexible solution via unobtrusive validation (not to count on HTML5):
Of course, there is a server-side check, too.
I don't think it's a good idea to cope with classes.
For instance, everything I show in the page is some class. This class has several enumerable type properties. It would be a nightmare to replicate all those properties, but making them nullable in some additional class as some ones suggested here on stackoverflow.
After all, why should i change my business logic for the sake of some specific markup? Instead, I deal with everything via javascript and some model checks.