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

后端 未结 10 1196
遇见更好的自我
遇见更好的自我 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:05

    I really liked @ScottRFrost's answer above. But, it fell two bricks short of my load as of this writing:

    1. It did not persist the groupings across postbacks inside my UpdatePanel and
    2. It did not persist the drop down selected value across postbacks.

    Here is my extensions to the client side of his answer:

    $(document).ready(function () {
    
        ddlOptionGrouping();
    
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(ddlOptionGrouping);
    
        function ddlOptionGrouping() {
            /* Add Option Groups to asp:DropdownList */
            var $select = $('#<%= aspDropDownList.ClientID %>');
            var optGroup;
            $('#<%= aspDropDownList.ClientID %> option').each(function () {
                if ($(this).val() == '<') {
                    /* Opener */
                    optGroup = $('').attr('label', $(this).text());
                } else if ($(this).val() == '>') {
                    /* Closer */
                    $('').appendTo(optGroup);
                    optGroup.appendTo($select);
                    optGroup = null;
                } else {
                    /* Normal Item */
                    let $option = $('').attr('value', $(this).val());
                    if (this.hasAttribute('selected')) {
                        $option.attr('selected', $(this).attr('selected'));
                    }
                    if (optGroup) {
                        $option.appendTo(optGroup);
                    } else {
                        $option.appendTo($select);
                    }
                }
                $(this).remove();
            });
        }
    });
    

提交回复
热议问题