Fill Asp.net dropdownlist using Jquery and JSON

In this article I am going to explain how to fill (bind) the Asp.net dropdownlist using Jquery and JSON.


Description:
We create a Webmethod to fill the Dropdownlist items. Data will be in JSON format.

Implementation:
I have created a table Tb_Country and insert some dummy records.

Id
int
CountryName
varchar(100)

Complete HTML Markup of webform:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "DorpdownJquery.aspx/GetCountry",
            data: "{}",
            dataType: "json",
            success: function (data) {
                $('#ddlCountry').append("<option value='0'>--Select--</option>");
                $.each(data.d, function (key, value) {
                    $("#ddlCountry").append($("<option></option>").val(value.Id).html(value.CountryName));
                });
            },
            error: function (result) {
                alert("Error");
            }
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddlCountry" runat="server">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>


Add the namespace
C# Code:

using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

VB.net Code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services

Create Webmethod
Write the below given in code file:
C# Code:
public class country
    {
        public int Id { get; set; }
        public string CountryName { get; set; }
    }

    [WebMethod]
    public static country[] GetCountry()
    {
        List<country> list = new List<country>();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
        using (SqlCommand cmd = new SqlCommand("select Id,CountryName from Tb_Country", con))
        {
        con.Open();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        foreach (DataRow dtrow in dt.Rows)
        {
            country ctry = new country();
            ctry.Id = Convert.ToInt32(dtrow["Id"].ToString());
            ctry.CountryName = dtrow["CountryName"].ToString();
            list.Add(ctry);
        }
    }   
        return list.ToArray();
    }

VB.net Code:
  Public Class country
        Public Property Id() As Integer
            Get
                Return m_Id
            End Get
            Set(value As Integer)
                m_Id = Value
            End Set
        End Property
        Private m_Id As Integer
        Public Property CountryName() As String
            Get
                Return m_CountryName
            End Get
            Set(value As String)
                m_CountryName = Value
            End Set
        End Property
        Private m_CountryName As String
    End Class

    <WebMethod()> _
    Public Shared Function GetCountry() As country()
        Dim list As New List(Of country)()
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
        Using cmd As New SqlCommand("select Id,CountryName from Tb_Country", con)
            con.Open()
            Dim adp As New SqlDataAdapter(cmd)
            Dim dt As New DataTable()
            adp.Fill(dt)
            For Each dtrow As DataRow In dt.Rows
                Dim ctry As New country()
                ctry.Id = Convert.ToInt32(dtrow("Id").ToString())
                ctry.CountryName = dtrow("CountryName").ToString()
                list.Add(ctry)
            Next
        End Using
        Return list.ToArray()
    End Function

Build, run the application and check it.
DEMO:
Fill Asp.net dropdownlist using Jquery and JSON
   In this article we have learn how to fill dropdownlist using Jquery Ajax and JSON (C#, VB.net). I hope you enjoyed this article. Please post you comment, query and feedback about this article. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.  

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget