Friday, March 23, 2012

Bind Dropdown Using Javascript and Webservice

1) Add Webservice wsCountry.asmx

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Services;
using System.Web.Services;
using Test;
///


/// Summary description for wsCountry
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 wsCountry : System.Web.Services.WebService
{

    public wsCountry()
    {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }
  
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
    public List FindAllCountries()
    {
        List locations = new List();
        string connectionString = ConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand())
            {
                command.Connection = connection;
                command.CommandText = "SelectAllCountries";
                command.CommandType = CommandType.StoredProcedure;
                connection.Open();
                using (SqlDataReader dataReader = command.ExecuteReader())
                {
                    Location location;
                    if (dataReader != null)
                        while (dataReader.Read())
                        {
                            location = new Location();
                            location.CountryID = (int)dataReader["CountryID"];
                            location.CountryName = Convert.ToString(dataReader["CountryName"]);
                            locations.Add(location);
                        }
                }
            }
        }
        return locations;
    }
}
namespace Test
{
    [Serializable]
    public class Location
    {
        public int CountryID
        { get; set; }

        public string CountryName
        { get; set; }

    }
}



2) Add ASPX Page and Call web service method.
Add script manager
Add Service Reference in the script Manager
Call Web service on the page load and get result and add that result to Dropdown.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="BindDropDown.aspx.cs" EnableEventValidation="false"  Inherits="BindDropDown" %>




    Bind Dropdown


   


   

       
           
               
           

       

   

   

   

   
   
   



No comments:

ShareThis

Welcome

Welcome to Rajesh Prajapati, asp.net blog.
Here you can find some useful code and information about asp.net., c#, VB.net, SQL Server, Web Service, Web Designing etc