如何在C#的下拉列表中添加占位符

3

你好,我有一个下拉列表的代码,我想在那里添加占位符,我该如何添加?

<asp:DropDownList id="ddlyear" runat="server" >
                     <asp:ListItem >Experience</asp:ListItem>
                     <asp:ListItem>Fresher</asp:ListItem>
                     <asp:ListItem>1</asp:ListItem>
                     <asp:ListItem>2</asp:ListItem>
                     <asp:ListItem>3</asp:ListItem>
</asp:DropDownList>

我想展示像这样的内容: 在此输入图片描述
4个回答

7
你可以这样做:
    <asp:DropDownList id="ddlyear" runat="server" >
                     <asp:ListItem selected hidden>Experience</asp:ListItem>
                     <asp:ListItem>Fresher</asp:ListItem>
                     <asp:ListItem>1</asp:ListItem>
                     <asp:ListItem>2</asp:ListItem>
                     <asp:ListItem>3</asp:ListItem>
    </asp:DropDownList>

selected属性将其设置为默认值,而hidden属性防止它在展开列表中可见。

这是可能最简单的方法。


3

仅使用HTML是无法实现此功能的,您需要使用Html + jQuery。

<asp:DropDownList ID="ddlyear" runat="server">
    <asp:ListItem>Experience</asp:ListItem>
    <asp:ListItem>Fresher</asp:ListItem>
    <asp:ListItem>1</asp:ListItem>
    <asp:ListItem>2</asp:ListItem>
    <asp:ListItem>3</asp:ListItem>
</asp:DropDownList>

在此之后,您需要使用jQuery来通过删除和重新附加占位符来实现魔法。
<script>
var isChanged = false;
$(function () {
    $('#ddlyear').focusin(function () {
        if (!isChanged) {
// this removes the first item which is your placeholder if it is never changed
            $(this).find('option:first').remove();
        }
    });
    $('#ddlyear').change(function () {
// this marks the selection to have changed
        isChanged = true;
    });
    $('#ddlyear').focusout(function () {
        if (!isChanged) {
// if the control loses focus and there is no change in selection, return the first item
            $(this).prepend('<option selected="selected" value="0">Experience</option>');
        }
    });
});
</script>

请注意,您需要使用jQuery来进行操作,只需将其安装为NuGet软件包或手动下载并在aspx中进行声明即可。
<head runat="server">
    <title></title>
// Sample only, you can place it in any location or use any version
    <script src="../scripts/jquery-2.2.2.min.js"></script>
</head>

1

@amit

兄弟,试试这个....

<select placeholder="select your beverage">
<option value="" default="" selected="">select your beverage</option>
<option value="tea">Tea</option>
<option value="coffee">Coffee</option>
<option value="soda">Soda</option>
</select>

1
占位符属性不起作用,它只是因为你声明的第一个选项而显示。 - DevEstacion
这是“selected”,你可以添加“hidden”以使其不出现在列表中。 - II ARROWS

0
在许多情况下,将第一项设置为空或作为虚拟项是可以接受的。 “空”意味着该值为空,文本可以是任何您想要的内容。
像这样:
<asp:DropDownList id="ddlyear" runat="server">
    <asp:ListItem Value="">Select</asp:ListItem>
    <asp:ListItem Value="Experience">Experience</asp:ListItem>
    <asp:ListItem Value="Fresher">Fresher</asp:ListItem>
    <asp:ListItem Value="1">1</asp:ListItem>
    <asp:ListItem Value="2">2</asp:ListItem>
    <asp:ListItem Value="3">3</asp:ListItem>
</asp:DropDownList>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接