Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Bind Dropdownlist in ASP.NET using jQuery AJAX

0.00/5 (No votes)
26 Nov 2013 2  
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:

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:

[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:

$(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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here