In this article I will explain how to populate CheckBoxList control from database on client side using jQuery AJAX, JSON and Web Method in ASP.Net using C# and VB.Net.
Just like the ASP.Net server side CheckBoxList, this jQuery CheckBoxList also supports the RepeatColumns property using which one can repeat the CheckBoxes in multiple columns.
This article will also explain how to get the Selected Text and Value of the ASP.Net CheckBoxList populated using jQuery AJAX on Button click.
Database
I have made use of the following table Fruits with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of an ASP.Net CheckBoxList and a Button. The CheckBoxList must have a dummy ListItem otherwise it will not be rendered in HTML and will not get populated using jQuery AJAX.
<asp:CheckBoxList ID="chkFruits" runat="server" RepeatColumns="2">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:CheckBoxList>
<asp:Button Text="Submit" runat="server" OnClick="Submit" />
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
WebMethod to get the records from database
You will need to implement the following WebMethod on your page which will get the records from the database and populate a list of .Net inbuilt ListItem class objects by storing the Fruit name in the Text and the Fruit Id in the Value property of the ListItem object.
Finally the List of ListItem objects are returned by the WebMethod.
C#
[WebMethod]
public static List<ListItem> GetFruits()
{
string query = "SELECT FruitId, FruitName FROM Fruits";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
List<ListItem> fruits = new List<ListItem>();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
fruits.Add(new ListItem
{
Text = sdr["FruitName"].ToString(),
Value = sdr["FruitId"].ToString()
});
}
}
con.Close();
}
}
}
}
return fruits;
}
VB.Net
<WebMethod()> _
Public Shared Function GetFruits() As List(Of ListItem)
Dim query As String = "SELECT FruitId, FruitName FROM Fruits"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim fruits As New List(Of ListItem)()
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
fruits.Add(New ListItem() With { _
.Text = sdr("FruitName").ToString(), _
.Value = sdr("FruitId").ToString() _
})
End While
End Using
con.Close()
End Using
End Using
End Using
End Using
Return fruits
End Function
jQuery implementation to populate the CheckBoxList control on client side
Inside the jQuery document load event, first a jQuery AJAX call is made to the WebMethod which then returns the list of Fruits in JSON format.
The returned JSON data is processed inside the Success event handler where first the RepeatColumns property is accessed using which it is determined in how many columns the CheckBoxList has to be repeated.
Then a loop is executed over the list of JSON data and a table row with cells consisting of a CheckBox and a Label are added to the existing CheckBoxList.
Each CheckBox is assigned a common name “FruitId” as the name will be used on server side to access the value of the selected CheckBoxes.
Finally a click event handler is attached to each CheckBox inside the CheckBoxList. Inside this event handler, if the CheckBox is checked then a Hidden field is added. The text part is extracted from the Label and is set to the value of the Hidden field.
For all hidden fields the name is set to “FruitName”, as the name will be used on server side to access the Text of the selected CheckBoxes in the CheckBoxList.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetFruits",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
function OnSuccess(r) {
var fruits = r.d;
var repeatColumns = parseInt("<%=chkFruits.RepeatColumns%>");
if (repeatColumns == 0) {
repeatColumns = 1;
}
var cell = $("[id*=chkFruits] td").eq(0).clone(true);
$("[id*=chkFruits] tr").remove();
$.each(fruits, function (i) {
var row;
if (i % repeatColumns == 0) {
row = $("<tr />");
$("[id*=chkFruits] tbody").append(row);
} else {
row = $("[id*=chkFruits] tr:last-child");
}
var checkbox = $("input[type=checkbox]", cell);
//Set Unique Id to each CheckBox.
checkbox[0].id = checkbox[0].id.replace("0", i);
//Give common name to each CheckBox.
checkbox[0].name = "FruitId";
//Set the CheckBox value.
checkbox.val(this.Value);
var label = cell.find("label");
if (label.length == 0) {
label = $("<label />");
}
//Set the 'for' attribute of Label.
label.attr("for", checkbox[0].id);
//Set the text in Label.
label.html(this.Text);
//Append the Label to the cell.
cell.append(label);
//Append the cell to the Table Row.
row.append(cell);
cell = $("[id*=chkFruits] td").eq(0).clone(true);
});
$("[id*=chkFruits] input[type=checkbox]").click(function () {
var cell = $(this).parent();
var hidden = cell.find("input[type=hidden]");
var label = cell.find("label");
if ($(this).is(":checked")) {
//Add Hidden field if not present.
if (hidden.length == 0) {
hidden = $("<input type = 'hidden' />");
cell.append(hidden);
}
hidden[0].name = "FruitName";
//Set the Hidden Field value.
hidden.val(label.text());
cell.append(hidden);
} else {
cell.remove(hidden);
}
});
};
</script>
Accessing the Text and Value of the checked (selected) CheckBoxes on PostBack
As discussed earlier, the Text and Value of the checked (selected) CheckBoxes are accessed inside the Button click event handler.
The values are extracted by passing the name of the CheckBox and the Hidden Field to the Request.Form collection to get the Ids and names of the selected Fruits respectively.
C#
protected void Submit(object sender, EventArgs e)
{
string fruitIds = Request.Form["FruitId"];
string fruitNames = Request.Form["FruitName"];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Id: " + fruitIds + "\\nText: " + fruitNames + "');", true);
}
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
Dim fruitIds As String = Request.Form("FruitId")
Dim fruitNames As String = Request.Form("FruitName")
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Id: " & fruitIds & "\nText: " & fruitNames + "');", True)
End Sub
Demo
Downloads