Json, Jquery, $.ajax(), asp.net and c# to get ajaxed data table rows passing multiple parameters





Json, Jquery, $.ajax(), asp.net and c# to get ajaxed data table rows passing multiple parameters

I got a request from my client that before creating user they want to see the list of existing users with the like first name and last name.

I didn’t want to use asp.net ajax update panel and full post back as its extremely slow, I used Jquery $ajax which is excellent

I planned to use Jquery ajax, as we know to use Jquery we need to get our results in Json format. Then we need to format json result using javascript to show the user friendly data to users.

I started working through my solution

First shock I got

JavaScriptSerializer js = new JavaScriptSerializer();

js.Serialize(rows, sb);

above method serializes the object passed to it to Json , you know what I passed as my object to this method, I passed my data table rows in it and it failed then I passed table in it and it failed so I started looking for the solution over the internet found quite few solutions but them were not fitting to my need one found in asp.net forums was fitting to my need btu there were errors in the code then I managed to resolve those erros . [sb is StringBuilder] used in my method].

Div to show the result

Following is the result div in which I’ll be showing my final resutl on asp.net page

<div id="divAjax"></div>
 
<asp:button ID="btnAdd" runat="server" Text="Create new user" OnClick="btnAdd_Click" OnClientClick="findUserBeforeCreate()"></asp:button>

This is the page method which takes first name an last name as input parameters passed and returns json result as string.

[WebMethod]
 
public static string FindUsersAjax(string firstName, string lastName)
 
{
 
StringBuilder sb = new StringBuilder();
 
string strFind = String.Format("FirstName like '{0}%' AND LastName like '{1}%' ", firstName.Trim(), lastName.Trim());
 
DataTable dt = GetDataSet().Tables[0];
 
List<dictionary <string, object>> rows = new List</dictionary><dictionary <string, object>>();
 
Array.ForEach(
 
dt.Select(), delegate(DataRow row)
 
{
 
Dictionary<string , object> Dictionary = new Dictionary</string><string , object>();
 
foreach (DataColumn col in dt.Columns)
 
Dictionary.Add(col.ColumnName, row[col].ToString());
 
rows.Add(Dictionary);
 
}
 
);
 
JavaScriptSerializer js = new JavaScriptSerializer();
 
js.Serialize(rows, sb);
 
return sb.ToString();
 
}
</string></dictionary>

Following Java Script function which, I am calling on the click event of the button calls the c# method it first name and last name as input parameters which then are passed to c# method.

function findUserBeforeCreate() {
 
var lastName = $("#< %=txtLastName.ClientID%>").val();
 
var firstName = $("#< %=txtFirstName.ClientID%>").val();
 
if (lastName.length < = 0 || firstName.length <= 0) {
 
$("#divAjax").html("Please enter names");
 
$("#divAjax").show('fast');
 
return false;
 
}
 
else {
 
&nbsp;
 
$.ajax({
 
type: "POST",
 
url: location.pathname + "/FindUsersAjax",
 
data: "{firstName:'" + firstName + "',lastName:'" + lastName + "'}",
 
contentType: "application/json; charset=utf-8",
 
datatype: "jsondata",
 
success: function(response) {
 
if (response.length <= 4) {
 
$("#divAjax").html("Nothing found");
 
$("#divAjax").show("fast");
 
}
 
else {
var myObject = eval(response.d);
BuildTable(myObject);
//$("#divAjax").html(myObject);
$("#divAjax").show("fast");
}
},
 
error: function(response) {
alert(response.status + ' ' + response.statusText);
}
});
}
}

Following C# code willl generate dummy data for you

 
private static DataSet GetDataSet()
 
{
 
DataSet ds = new DataSet("myDataSet");
 
DataTable t = new DataTable("TableName");
 
DataColumn c = new DataColumn("UserID");
 
DataColumn c2 = new DataColumn("Password");
 
DataColumn c3 = new DataColumn("FirstName");
 
DataColumn c4 = new DataColumn("LastName");
 
t.Columns.Add(c); t.Columns.Add(c2);
 
t.Columns.Add(c3); t.Columns.Add(c4);
 
ds.Tables.Add(t);
 
&nbsp;
 
for (int Index = 1; Index < = 10; Index++)
 
{
 
DataRow r = t.NewRow();
 
r[0] = Index.ToString();
 
r[1] = "password" + r[0];
 
r[2] = "FirstName" + r[0];
 
r[3] = "LastName" + r[0];
 
t.Rows.Add(r);
 
}
 
return ds;
 
}

Struggle point: I was returning Results in Json but JavaScript eval function was not working for me and it took few hours to resolve the issue thanks to

var myObject = eval(response.d);

OR

var myObject= eval("("+ eval( response) + ")");

I was using it like var myObject= eval(“(“+ response + “)”); and struggled as it was treating result as single string not as an array, then using it in this way It worked for me var myObject= eval(“(“+ eval( response) + “)”);
Following java script function is to create table to show the users

function BuildTable(msg) {
if ($('#tblResult').length != 0) // remove table if it exists
{ $("#tblResult").remove(); }
var table = '<table id=tblResult><thead> <tr><th>User Id</th>  <th>Password</th>  <th>First Name</th>  <th>Last Name</th></tr></thead>  <tbody>';
for (var i = 0; i < = msg.length - 1; i++) {
var row = '<tr>';
row += '<td>' + msg[i].UserID + '</td>';
row += '<td>' + msg[i].Password + '</td>';
row += '<td>' + msg[i].FirstName + '</td>';
row += '<td>' + msg[i].LastName + '</td>';
row += '';
table += row;
}
table += '</tbody></table>';
$('#divAjax').html(table);
}

Note: all code samples are for learning purpose please change them according to your own requirement. Please do not forget to secure your code against Sql and JavaScript injections.
Complete HTML Code is as follow

<html>
<head runat="server">
<script src="jquery-ui-1.8rc3.custom/js/jquery-1.4.2.min.js" type="text/javascript"></script>
<title>Ajax Data Table Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
First Name<asp:textbox ID="txtFirstName" runat="server"></asp:textbox>
Last Name<asp:textbox ID="txtLastName" runat="server"></asp:textbox>
</div>
<input id="Button1" type="button" value="Get Data" onclick="findUserBeforeCreate();" />
<div id="divAjax">
 
</div>
<script type="text/javascript">
function findUserBeforeCreate() {
var lastName = $("#< %=txtLastName.ClientID%>").val();
var firstName = $("#< %=txtFirstName.ClientID%>").val();
if (lastName.length < = 0 || firstName.length <= 0) {
 
$("#divAjax").html("Please enter names");
$("#divAjax").show('fast');
return false;
}
 
else {
$.ajax({
type: "POST",
url: location.pathname + "/FindUsersAjax",
data: "{firstName:'" + firstName + "',lastName:'" + lastName + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
success: function(response) {
if (response.length <= 4) {
$("#divAjax").html("Nothing found");
$("#divAjax").show("fast");
}
 
else {
var myObject = eval(response.d);
BuildTable(myObject);
//$("#divAjax").html(myObject);
$("#divAjax").show("fast");
}
},
 
error: function(response) {
alert(response.status + ' ' + response.statusText);
}
});
}
}
 
function BuildTable(msg) {
if ($('#tblResult').length != 0) // remove table if it exists
 
{ $("#tblResult").remove(); }
var table = '<table id=tblResult><thead> <tr><th>User Id</th>  <th>Password</th>  <th>First Name</th>  <th>Last Name</th></tr></thead>  <tbody>';
for (var i = 0; i < = msg.length - 1; i++) {
var row = '<tr>';
row += '<td>' + msg[i].UserID + '</td>';
row += '<td>' + msg[i].Password + '</td>';
row += '<td>' + msg[i].FirstName + '</td>';
row += '<td>' + msg[i].LastName + '</td>';
row += '';
table += row;
 
}
 
table += '</tbody>';
$('#divAjax').html(table);
}
</script>
</form>
</body>
</html>



Tags: , , , , , , , , , ,

11 Responses to “Json, Jquery, $.ajax(), asp.net and c# to get ajaxed data table rows passing multiple parameters”

  1. Jakub Konecki says:

    You should read about SQL Injection before you release the code from this article.

  2. nicholas says:

    Hi,
    I tried to use var myObject = eval(‘(‘ + myJSONtext + ‘)’); for json convert to javascript, but it not work for me. can you help me ?
    the error message: ‘]’ expect

    Thanks

  3. Naveed says:

    You can try

    var myObject = eval(’(’ + myJSONtext.d + ‘)’);

  4. Prawin says:

    Even Iam getting the same error. Iam using Firefox. Please help me out.
    Prawin

  5. Prawin says:

    Atlast it worked for me.

    In the http://www.javascriptkata.com/2007/05/08/how-to-use-json/#comment-710
    eval(“(“ + eval(theServerSideJsonTextResponse); + “)”) did your job..but it didn’t worked for me..

    I have used the following pice of code which worked exactly.
    var myObject = eval(‘(‘ + msg.d + ‘)’);

    Anywayss thanks for the article.

  6. nicholas says:

    Hi Naveed,
    ‘var myObject = eval(’(’ + msg.d + ‘)’);’ also worked for me. But finally I decided to use parse2.js instead of eval()..
    If you never use this json converter file, maybe you could try to use it.

    Thanks for your excellent article.

  7. salman says:

    Very Helpful article… 🙂

  8. cris_gomez says:

    The code below is not advisable since this is prone
    to sql injection.
    string strFind = String.Format(“FirstName like ‘{0}%’ AND LastName like ‘{1}%’ “, firstName.Trim(), lastName.Trim());

  9. Usman says:

    hi i have also used jQuery Datatable with ASP.net in C# the details can be found over
    http://usmanshabbir.blogspot.com/2010/10/simplest-way-to-use-jquery-datatable-in.html

  10. This blog has been updated today 15/03/2011 to work with JQuery 1.4+

  11. Anu says:

    Thanks for the article and this is really helpful