In this article I will explain with an example, how to populate
CheckBoxList control from database using
jQuery AJAX and
JSON in ASP.Net using C# and VB.Net.
Just like the 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
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 following controls:
CheckBoxList – For capturing user input.
The CheckBoxList consists of a ListItem.
The CheckBoxList has been assigned with the following property:
RepeatColumns – For specifying the number of columns in which the CheckBoxes will be displayed. In this case it will be 2 columns.
Button – For displaying Text and Value of the selected item.
The Button has been assigned with an OnClick event handler.
<asp:CheckBoxList ID="chkFruits" runat="server" RepeatColumns="2">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />
jQuery implementation to populate the CheckBoxList control on client side
Inside the HTML Markup, the following script is inherited:
1. jquery.min.js
Inside the
jQuery document ready event handler, first a
jQuery AJAX call is made to the
GetFruits WebMethod (discussed earlier) which returns the list of Fruits in
JSON format.
OnSuccess
The returned JSON data is processed inside the
Success event handle of the
jQuery AJAX call, where the
RepeatColumns property is accessed using which it is determined in how many columns the CheckBoxList has to be repeated.
Then, a FOR EACH 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 with a common name FruitId as the name will be used on Server-Side to access the value of the selected CheckBoxes.
And a check is performed if value of repeated columns is equal to 0 then the value is set to 1 which determines in how many columns the CheckBoxList has to be repeated.
After that, a click event handler is assigned to each CheckBox inside the CheckBoxList.
Inside the click event handler, a check is performed if the CheckBox is checked then a HiddenField is added to it. The Text part is extracted from the Label and is set to the value of the HiddenField.
For all HiddenFields 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="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/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>
Namespaces
You will need to import the following namespaces.
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Fetching records from Database using WebMethod (PageMethod)
Inside the
GetFruits WebMethod, a Generic List collection of ListItem class object is created and the connection is read from
Web.Config file.
Then, the connection is opened and records are fetched from the Fruits Table using ExecuteReader method and added as new item to Generic List collection of ListItem class object.
Finally, a Generic List collection of class object is returned.
C#
[WebMethod]
public static List<ListItem>GetFruits()
{
string sql = "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(sql, con))
{
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 sql 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(sql, con)
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
Return fruits
End Function
Accessing the Text and Value of the checked (selected) CheckBoxes
When the Submit Button is clicked, the values are fetched from the Request.Form collection.
C#
protected void Submit(object sender, EventArgs e)
{
string fruitIds = Request.Form["FruitId"];
string fruitNames = Request.Form["FruitName"];
ClientScript.RegisterClientScriptBlock(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.RegisterClientScriptBlock(Me.GetType(), "alert", "alert('Id: " & fruitIds & "\nText: " & fruitNames & "');", True)
End Sub
Screenshot
Demo
Downloads