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

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


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> rows = new List>();


dt.Select(), delegate(DataRow row)


Dictionary Dictionary = new Dictionary();

foreach (DataColumn col in dt.Columns)

Dictionary.Add(col.ColumnName, row[col].ToString());




JavaScriptSerializer js = new JavaScriptSerializer();

js.Serialize(rows, sb);

return sb.ToString();


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");


return false;


else {



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");



else {
var myObject = eval(response.d);

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);



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];



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);


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 = '';
for (var i = 0; i < = msg.length - 1; i++) {
var row = '';
row += '';
row += '';
row += '';
row += '';
row += '';
table += row;
table += '
User Id Password First Name Last Name
' + msg[i].UserID + '' + msg[i].Password + '' + msg[i].FirstName + '' + msg[i].LastName + '
'; $('#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

Ajax Data Table Example

First Name Last Name

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:

    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


  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.

  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

  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