How can I add option groups in ASP.NET drop down list?

后端 未结 10 1168
遇见更好的自我
遇见更好的自我 2020-11-28 10:22

I have a requirement of grouping the drop down list options in ASP.NET drop down server control. Do you have any idea to how to approach the issue? I am new to ASP.NET.

10条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 11:01

    I really like this client-side solution (doesn't need a custom DropDownList, but uses jQuery):

    backend

    private void _addSelectItem(DropDownList list, string title, string value, string group = null) {
       ListItem item = new ListItem(title, value);
       if (!String.IsNullOrEmpty(group))
       {
           item.Attributes["data-category"] = group;
       }
       list.Items.Add(item);
    }
    
    ...
    _addSelectItem(dropDown, "Option 1", "1");
    _addSelectItem(dropDown, "Option 2", "2", "Category");
    _addSelectItem(dropDown, "Option 3", "3", "Category");
    ...
    

    client

    var groups = {};
    $("select option[data-category]").each(function () {
         groups[$.trim($(this).attr("data-category"))] = true;
    });
    $.each(groups, function (c) {
         $("select option[data-category='"+c+"']").wrapAll('');
    });
    

提交回复
热议问题