How to Grouping List Items (option) in ASP.NET DropDownList control using Jquery.

Introduction

In this post, I am explaining how to Grouping List Items (option) in ASP.NET DropDownList control.
ASP.NET DropDownList control does not allow Items grouping feature. Here in this post I have explained how we can do this very easily with just a few jquery lines.

Features:

  • Bind dropdownlist from database data in ASP.NET Using Jquery.
  • Grouping Items in DropDownList Control.
  • Get dropdown selected value from Code behind.
  • Retain dropdownlist selected value after postback.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table for fetch data from Jquery function.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Webpage and Design for bind database data to dropdown list.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code
     
 <h3>Grouping List Items (option) in ASP.NET DropdownList Control.</h3>
    <table>
        <tr>
            <td>Select Country : </td>
            <td>
                <asp:DropDownList ID="ddCountry" runat="server"></asp:DropDownList>
            </td>
            <td>
                <asp:Button ID="btnGetValue" runat="server" Text="Get Selected Value" OnClick="btnGetValue_Click" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:HiddenField ID="hfSelectedValue" runat="server" />
            </td>
            <td colspan="2">
                <asp:Label ID="lblMsg" runat="server"></asp:Label>
            </td>
        </tr>
    </table>
JS Code
     
    <script src="Scripts/jquery-1.7.1.js"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $('#<%=ddCountry.ClientID %>').append(
                    $('<option></option>').val('0').html('Please Wait...')
                );
            $.ajax({
                url: "Default.aspx/GetCountry",
                data: "{}",
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: OnSuccess,
                error: OnError
            });
            // for get selected value from code behind
            $('#<%= ddCountry.ClientID%>').change(function () {
                $('#<%= hfSelectedValue.ClientID%>').val($('#<%=ddCountry.ClientID%>').val());
            });

        });
        function OnSuccess(data) {
            $('#<%=ddCountry.ClientID%>').empty();
            var d = data.d;
            var dropdown = $('#<%=ddCountry.ClientID%>');
            var zone = "";
            var optGroup;

            for (var i = 0; i < d.length; i++) {
                if (d[i].Zone.toString() != zone) {
                    optGroup = $("<optgroup style='background-color:#CCCC00' />");
                    optGroup.attr('label', d[i].Zone.toString());
                }
                zone = d[i].Zone.toString();
                optGroup.append(
                        $('<option></option>').val(d[i].CountryID.toString()).html(d[i].CountryName.toString())
                    );

                dropdown.append(optGroup);
            }
            //for keep value after postback           
            $('#<%=ddCountry.ClientID%>').val($('#<%=hfSelectedValue.ClientID%>').val());
        }

        function OnError() {
            alert("Failed!");
        }

    </script>

Step-6: Write this function into your page code behind.


Must have to do this EnableEventValidation="false" into your page.
            
     [WebMethod]
        public static List<CountryMaster> GetCountry()
        {
            
            List<CountryMaster> country = new List<CountryMaster>();
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                country = dc.CountryMasters.ToList();
            }
            return country;
        }

Step-7: Write this code into button_click event for get selected value from code behind.


            
    protected void btnGetValue_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "Selected Value is : " + hfSelectedValue.Value;
        }

Step-8: Run Application.





Related Posts:




Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.