asp.net dropdownlist - add blank line before db values

让人想犯罪 __ 提交于 2019-11-30 04:18:47

You can simply add a ListItem inside the DropDownList Markup. All the values from the DataSource will be appended after that.

<asp:DropDownList ID="drpClient" runat="server" Width="200px" 
          AutoPostBack="True" DataSourceID="dsClients" DataTextField="name" 
          DataValueField="client_id" AppendDataBoundItems="true">
   <asp:ListItem>-- pick one --</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="drpClient" runat="server" Width="200px" 
        AutoPostBack="True" DataSourceID="dsClients" DataTextField="name" 
        DataValueField="client_id" AppendDataBoundItems="True">

    <asp:ListItem Text="" Value="" />
 </asp:DropDownList>

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.

protected void DropDownList_DataBound(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        ListItem emptyItem = new ListItem("", "");
        ddl.Items.Insert(0, emptyItem);
    }

I solve changing the select command adding an empty option:

        <asp:SqlDataSource ID="dsClients" runat="server" 
            ConnectionString="my_connection_string" 
            ProviderName="System.Data.SqlClient" 
            SelectCommand="SELECT [client_id], [name] FROM [clients] union SELECT NULL, '--- pick one ----' ">
        </asp:SqlDataSource>

Greetings!!!

In razor-style implementation at me it looks like this:

@Html.EnumDropDownListFor(
    model => model.Privilege.Role,
    "-- Select role --",
    new
    {
        @style = "width: 216px !important",
        @class = "form-control",
        id = "role",
        required = "required"
     })

And in javascript which is executed on load I have this:

function PutDefaultPrivilegePanelListHints() {
    $('#role').val('');
    ...
}

There is also more flexible solution via unobtrusive validation (not to count on HTML5):

$('.required').each(function () { $(this).rules('add', { required: true, messages: { required: '' } }) });

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!