Click here to Skip to main content
12,633,764 members (32,258 online)
Click here to Skip to main content
Add your own
alternative version

Stats

82.6K views
2.2K downloads
20 bookmarked
Posted

Bind Dropdownlist in ASP.NET using jQuery AJAX

, 26 Nov 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Amol Jadhao
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.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionUsing Master Page Pin
Member 1110266014-Dec-14 19:24
memberMember 1110266014-Dec-14 19:24 
GeneralMy vote of 2 Pin
Member 1110266014-Dec-14 19:23
memberMember 1110266014-Dec-14 19:23 
Questionwhat does "d" in Result mean? Pin
tara_sh50019-Oct-14 16:43
membertara_sh50019-Oct-14 16:43 
AnswerRe: what does "d" in Result mean? Pin
Amol Jadhao19-Oct-14 20:59
memberAmol Jadhao19-Oct-14 20:59 
QuestionThanks for help Pin
Member 1114571011-Oct-14 4:22
memberMember 1114571011-Oct-14 4:22 
QuestionMessage Automatically Removed Pin
31-May-14 1:16
memberMerbin Joe31-May-14 1:16 
QuestionMessage Automatically Removed Pin
19-Feb-14 4:26
memberMember 1014497619-Feb-14 4:26 
QuestionBasic Pin
Member 436622026-Nov-13 8:44
memberMember 436622026-Nov-13 8: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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161208.2 | Last Updated 26 Nov 2013
Article Copyright 2013 by Amol Jadhao
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid