2

我正在处理一个较旧的 ASP.NET 项目(我认为不是 MVC),他们需要的功能之一是当他们将鼠标悬停在下拉列表中的项目上时查看项目的描述。这可以通过使用以下代码并使用标题文本的 HTML 来简单地完成:

<select>
    <option value="1" title="Option 1 Desc">Option 1</option>
    <option value="2" title="Option 2 Desc">Option 2</option>
    <option value="3" title="Option 3 Desc">Option 3</option>
</select>

好的,那么如何使用 ASP.NET DropDownList 控件来执行此操作?我有以下代码:

<asp:DropDownList ID="DropDownListLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownListLocation_OnSelectedIndexChanged" CssClass="editorFieldServerControl" ClientIDMode="Static"></asp:DropDownList>

在“代码背后”页面中:

private void PopulateFacilityDropdown(List<FacilityAvailableByLocation> facilities, int? selectedID)
{
    DropDownListFacility.DataSource = facilities;
    DropDownListFacility.DataTextField = "FacilityName";
    DropDownListFacility.DataValueField = "FacilityID";
    DropDownListFacility.DataBind();            
    DropDownListFacility.Items.Insert(0, new System.Web.UI.WebControls.ListItem("", ""));                   

    if (selectedID.HasValue && selectedID.Value > 0)
        DropDownListFacility.SelectedIndex = facilities.FindIndex(b => b.FacilityID == selectedID.Value);
        else DropDownListFacility.SelectedIndex = 0;
    }
}

基本上,设施列表中的每个设施都有我可以退出的 ID、名称、描述的属性。我只想能够在每个<option>渲染的标题上放置一个标题属性并将描述放入其中。或者能够为每个<option>标签添加一个自定义属性,如“数据描述”,然后我可以使用一点 jQuery 自己将标题添加到每个选项标签中,这很容易。

我怀念那些您可以循环浏览列表并手动输出自定义下拉代码的日子。

有任何想法吗?非常感谢

4

1 回答 1

7

You can manually add a title attribute to each list item like this. Give it a shot:

    private void PopulateFacilityDropdown(List<FacilityAvailableByLocation> facilities, int? selectedID)
    {
        DropDownListFacility.DataSource = facilities;
        DropDownListFacility.DataTextField = "FacilityName";
        DropDownListFacility.DataValueField = "FacilityID";
        DropDownListFacility.DataBind();            
        DropDownListFacility.Items.Insert(0, new System.Web.UI.WebControls.ListItem(String.Empty, String.Empty);                   

        foreach (FacilityAvailableByLocation f in facilities)
        {
            DropDownListFacility.Items.FindByValue(f.FacilityID).Attributes.Add("title", f.TitleDescription);
        }

        if (selectedID.HasValue && selectedID.Value > 0)
            DropDownListFacility.SelectedIndex = facilities.FindIndex(b => b.FacilityID == selectedID.Value);
            else DropDownListFacility.SelectedIndex = 0;
        }
    }

f.TitleDescription would be the property you want the title to be.

于 2012-10-01T03:40:12.687 回答