Click here to Skip to main content
15,884,099 members
Articles / Web Development / ASP.NET
Tip/Trick

Bind Dropdownlist in ASP.NET using jQuery AJAX

Rate me:
Please Sign up or sign in to vote.
4.78/5 (14 votes)
26 Nov 2013CPOL1 min read 139.2K   2.7K   20   8
How to bind dropdownlist in ASP.NET using JQuery Ajax

Introduction

This tip will help you to understand how to bind a DropDownList by calling a web service from jQuery AJAX in ASP.NET. I am using the same concept to create a web method in a web service and call those methods in jQuery.

Using the Code

First, you need to create a sample table in the database. I am creating a country table in the database. We need to design a table in the database to get data from the database.

Sample Image - maximum width is 600 pixels

After completion of table design, enter some of the country names in the database to work for our sample. Now, we will create a web method in the web service and we will use that method to call it from jQuery. You need to follow the steps given below.

Step 1: Create an ASP.NET Web Service

So, add an .asmx page to the current solution and modify the code as in the following example:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
namespace Jquery_Webservice
{
    /// <summary>
    /// Summary description for CountryDetails
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, 
    // using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class CountryDetails : System.Web.Services.WebService
    {
        public class CountryInfo
        {
            public int CountryId{get;set;}
            public string CountryName{get;set;}
        }
        public List<countryinfo> CountryInformation { get; set; }
        [WebMethod]
        public List<countryinfo> LoadCountry()
        {
            CountryInfo ci = new CountryInfo();
            List<countryinfo> CountryInformation = new List<countryinfo>();
            DataSet ds;
            using (SqlConnection con = new SqlConnection
            ("Data Source=xxxx;User Id=xxxx;Password=xxxx;DataBase=xxxx"))
            {
                using (SqlCommand cmd = new SqlCommand("select * from Tbl_Country", con))
                {
                    con.Open();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {

                        ds = new DataSet();
                        da.Fill(ds);
                    }
                }
            }
            try
            {
                if (ds != null)
                {
                    if (ds.Tables.Count > 0)
                    {
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                CountryInformation.Add(new CountryInfo()
                                {
                                    CountryId = Convert.ToInt32(dr["CountryId"]),
                                    CountryName = dr["CountryName"].ToString()
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return CountryInformation;
        }
    }
}

Don't forget to enable the attribute:

C#
[System.Web.Script.Services.ScriptService] 

before the class definition.

The second step is to add the [Web Method] attribute before the function definition. So, here we have finished our Service settings. We can run this service to test it in a Web browser. Now we will set up a jQuery AJAX function to call the service.

Step 2: Implement jQuery AJAX

First, you need to add the jQuery library in your page:

JavaScript
$(document).ready(function () {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "CountryDetails.asmx/LoadCountry",
        data: "{}",
        dataType: "json",
        success: function (Result) {
               Result=Result.d;
            $.each(Result, function (key, value) {
                $("#ddlcountry").append($("<option></option>").val
                (value.CountryId).html(value.CountryName));
            });
          // Another way of writing
            //  for (var i = 0; i < Result.length; i++) {
            // $("#ddlcountry").append("<option value=" + Result[i].ID + ">" + 
            //     Result[i].Name + "</option>");
            //  }

          // One more way of writing
            // for (var i in Result) {
            //  $("#ddlcountry").append($("<option></option>").val(Result[i].ID).
            //   text(Result[i].Name));
            //  }

        },
        error: function (Result) {
            alert("Error");
        }
    });
});

Points of Interest

This is only a simple demonstration to show the process of binding a DropDownList via a web service. In this example, we have used a SQL Server database, Data Adapter, and DataSet. Don't forget to enable the attribute [System.Web.Script.Services.ScriptService], and add the [Web Method] attribute before the function definition.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer At Lycos Internet Ltd
India India
Amol Jadhao is a ASP.Net Developer
He holds Bachelor's degree in Computer Engineering.
His core skills are ASP.NET,C#.NET,ADO.NET,SQL SERVER,WEB SERVICES,JAVA SCRIPT,JQUERY,AJAX,HTML,CSS.

Comments and Discussions

 
QuestionUsing Master Page Pin
Member 1110266014-Dec-14 18:24
Member 1110266014-Dec-14 18:24 
1) We can call as normal web method, instead of "Web Service" method. 

2) Using Master Page, drop down control id is not taken, to overcome this issue, use, (ClientIDMode="Static"). At run time dropdown control id won't change.
<asp:DropDownList ID="ddlTeam" style="width:auto" runat="server" ClientIDMode="Static"></asp:DropDownList>

GeneralMy vote of 2 Pin
Member 1110266014-Dec-14 18:23
Member 1110266014-Dec-14 18:23 
Questionwhat does "d" in Result mean? Pin
tara_sh50019-Oct-14 15:43
tara_sh50019-Oct-14 15:43 
AnswerRe: what does "d" in Result mean? Pin
Amol Jadhao19-Oct-14 19:59
Amol Jadhao19-Oct-14 19:59 
QuestionThanks for help Pin
Member 1114571011-Oct-14 3:22
Member 1114571011-Oct-14 3:22 
QuestionBasic Pin
Member 436622026-Nov-13 7:44
Member 436622026-Nov-13 7:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.