In this article I will explain with an example, how to populate
DataList control by binding
DataSet on Client-Side using
jQuery AJAX in ASP.Net with C# and VB.Net.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
HTML Markup
The HTML Markup consists of following control:
DataList – For displaying data.
The
DataList consists of one
ItemTemplate.
ItemTemplate – The ItemTemplate contains Eval function for binding columns.
<asp:DataList ID="dlCustomers" runat="server" RepeatLayout="Table" RepeatColumns="3" CellPadding="2" CellSpacing="2">
<ItemTemplate>
<table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px; border: dashed 2px #04AFEF; background-color: #B0E2F5">
<tr>
<td><b><u><span class="name"><%# Eval("ContactName") %></span></u></b></td>
</tr>
<tr>
<td>
<b>City: </b><span class="city"><%# Eval("City") %></span><br />
<b>Postal Code: </b><span class="postal"><%# Eval("PostalCode") %></span><br />
<b>Country: </b><span class="country"><%# Eval("Country")%></span><br />
<b>Phone: </b><span class="phone"><%# Eval("Phone")%></span><br />
<b>Fax: </b><span class="fax"><%# Eval("Fax")%></span><br />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
Populating ASP.Net DataList by binding DataSet Client Side using jQuery AJAX
Inside the HTML Markup, the following script file is inherited.
1. jquery.min.js
Inside the
jQuery document ready event handler, the input
TextBox is set to hide and a
jQuery AJAX call is made to the
GetCustomers WebMethod (PageMethod).
Inside the Success event handler, the ternary conditional operator of RepeatColumns is converted into integer.
Then, WHILE loop is executed, inside the WHILE loop an FOR loop is executed and a variable is declared.
A check is performed if customer length is equal to 0 then the last row is remove if not then, rows are created and appended to the
DataList control.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=dlCustomers]").hide();
$.ajax({
type: "POST",
url: "Default.aspx/GetCustomers",
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(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Table");
var repeatColumns = parseInt("<%=dlCustomers.RepeatColumns == 0 ? 1 : dlCustomers.RepeatColumns %>");
var rowCount = Math.ceil(customers.length / repeatColumns);
var i = 0;
while (i < repeatColumns * rowCount) {
var row = $("[id*=dlCustomers] tr").eq(0).clone(true);
for (var j = 0; j < repeatColumns; j++) {
var customer = $(customers[i]);
if (customer.length == 0) {
$("table:last", row).remove();
} else {
$(".name", row).eq(j).html(customer.find("ContactName").text());
$(".city", row).eq(j).html(customer.find("City").text());
$(".postal", row).eq(j).html(customer.find("PostalCode").text());
$(".country", row).eq(j).html(customer.find("Country").text());
$(".phone", row).eq(j).html(customer.find("Phone").text());
$(".fax", row).eq(j).html(customer.find("Fax").text());
}
i++;
}
$("[id*=dlCustomers]").append(row);
}
$("[id*=dlCustomers] tr").eq(0).remove();
$("[id*=dlCustomers]").show();
}
</script>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Binding the DataList using C# and VB.Net
Inside the Page_Load event handler, the BindData method is called where a DataTable class object is created and dynamic data is added into it.
Then, a ternary conditional operator is used, if RepeatColumns is equal to 0 then count will be set to 1 otherwise RepeatColumns value is set.
Finally, a FOR loop is executed and rows are added to the
DataTable. Which is later used to populate the
DataList control.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
DataTable dt = new DataTable();
dt.Columns.Add("CustomerID");
dt.Columns.Add("ContactName");
dt.Columns.Add("Country");
dt.Columns.Add("City");
dt.Columns.Add("PostalCode");
dt.Columns.Add("Phone");
dt.Columns.Add("Fax");
int count = dlCustomers.RepeatColumns == 0 ? 1 : dlCustomers.RepeatColumns;
for (int i = 0; i < count; i++)
{
dt.Rows.Add();
}
dlCustomers.DataSource = dt;
dlCustomers.DataBind();
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindData()
End If
End Sub
Private Sub BindData()
Dim dt As DataTable = New DataTable()
dt.Columns.Add("CustomerID")
dt.Columns.Add("ContactName")
dt.Columns.Add("Country")
dt.Columns.Add("City")
dt.Columns.Add("PostalCode")
dt.Columns.Add("Phone")
dt.Columns.Add("Fax")
Dim count As Integer = If(dlCustomers.RepeatColumns = 0, 1, dlCustomers.RepeatColumns)
For i As Integer = 0 To count - 1
dt.Rows.Add()
Next
dlCustomers.DataSource = dt
dlCustomers.DataBind()
End Sub
WebMethod (PageModel) to handle jQuery AJAX call
Inside the
GetCustomers WebMethod, the SQL query is passed to the SqlCommand as a parameter and
GetData method is returned.
Note: The following
WebMethod is declared as
static (C#) and
Shared (VB.Net), it is decorated with
WebMethod attribute, this is necessary otherwise the method will not be called from client side
jQuery AJAX call.
Inside the GetData method, the records are fetched from the Customers Table of Northwind database.
C#
[WebMethod]
public static string GetCustomers()
{
string sql = "SELECT ContactName, City, PostalCode, Country, Phone, Fax FROM Customers";
SqlCommand cmd = new SqlCommand(sql);
return GetData(cmd).GetXml();
}
private static DataSet GetData(SqlCommand cmd)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.Connection = con;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
VB.Net
<WebMethod>
Public Shared Function GetCustomers() As String
Dim sql As String = "SELECT ContactName, City, PostalCode, Country, Phone, Fax FROM Customers"
Dim cmd As New SqlCommand(sql)
Return GetData(cmd).GetXml()
End Function
Private Shared Function GetData(cmd As SqlCommand) As DataSet
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using ds As New DataSet()
sda.Fill(ds)
Return ds
End Using
End Using
End Using
End Function
Screenshot
Demo
Downloads