Introduction:
In this article I am going to explain with
example How to bind asp.net dropdown list dynamically from sql server database
by using jquery AJAX and json.
Implementation:
Create a
table (Dept_Table) with the columns and their data type as shown below
Column
Name
|
Data
Type
|
DeptId
|
Int (primary key. Set is identity=true)
|
DeptName
|
varchar(50)
|
Then insert some data into this table.
Now create
the connection string in web.config file as:
<connectionStrings>
<add name="Empcon" connectionString="Data Source=localhost;Initial Catalog=test;Integrated
Security=True"/>
</connectionStrings>
HTML Source Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind DropDownList with database table using jquery ajax </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
//url is the
path of our web method (Page name/function name)
url: "Default.aspx/PopulateDropDownList",
data: "{}",
dataType: "json",
//called on
jquery ajax call success
success: function (result) {
$('#ddlDepartments').empty();
$('#ddlDepartments').append("<option value='0'>--Select--</option>");
$.each(result.d, function (key, value) {
$("#ddlDepartments").append($("<option></option>").val(value.DeptId).html(value.DeptName));
});
},
//called on
jquery ajax call failure
error: function ajaxError(result)
{
alert(result.status + ' : ' + result.statusText);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset style="width:310px;">
<legend>Populate DropDownList using jQuery AJAX</legend>
Select Department: <asp:DropDownList ID="ddlDepartments" runat="server" Width="160px" />
</fieldset>
</div>
</form>
</body>
</html>
Asp.Net C# Code to fill
dropdownlist dynamically using jquery ajax
In code file (Default.aspx.cs)
write the code:
Include
required namespaces
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
then write the code as:
protected void Page_Load(object sender, EventArgs e)
{
}
public class Department
{
public int DeptId { get; set; }
public string DeptName { get; set; }
}
[WebMethod]
public static List<Department>
PopulateDropDownList()
{
DataTable dt = new DataTable();
List<Department> objDept = new List<Department>();
using (SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["EmpCon"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT DeptId,DeptName FROM Dept_Table", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count
> 0)
{
for (int i = 0; i <
dt.Rows.Count; i++)
{
objDept.Add(new Department
{
DeptId = Convert.ToInt32(dt.Rows[i]["DeptId"]),
DeptName = dt.Rows[i]["DeptName"].ToString()
});
}
}
return objDept;
}
}
}
Asp.Net VB Code to fill
dropdownlist dynamically using jquery ajax
In code file (Default.aspx.vb) write the code:
Import required
namespaces
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Then write the code as:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Class Department
Public Property DeptId() As Integer
Get
Return m_DeptId
End Get
Set(value As Integer)
m_DeptId = Value
End Set
End Property
Private m_DeptId As Integer
Public Property DeptName() As String
Get
Return m_DeptName
End Get
Set(value As String)
m_DeptName = Value
End Set
End Property
Private m_DeptName As String
End Class
<WebMethod> _
Public Shared Function PopulateDropDownList() As List(Of Department)
Dim dt As New DataTable()
Dim objDept As New List(Of Department)()
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("EmpCon").ConnectionString)
Using cmd As New SqlCommand("SELECT DeptId,DeptName FROM Dept_table", con)
con.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
If dt.Rows.Count
> 0 Then
For i As Integer = 0 To dt.Rows.Count
- 1
objDept.Add(New Department() With { _
.DeptId = Convert.ToInt32(dt.Rows(i)("DeptId")), _
.DeptName = dt.Rows(i)("DeptName").ToString() _
})
Next
End If
Return objDept
End Using
End Using
End Function
0 comments:
Post a Comment