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 extremly 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 solotion over the internet found quite few solutions but them were not fitting to my need one found in asp.net foums was fitting to my need btu there were errors in teh 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()” />
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();
UsersService userService = new UsersService();
string strFind = String.Format(“FirstName like ‘{0}%’ AND LastName like ‘{1}%’ “, firstName.Trim(), lastName.Trim());
DataTable dt = userService.FindUsers(strFind).Tables[0];
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Array.ForEach(
dt.Select(), delegate(DataRow row)
{
Dictionary<string, object> Dictionary = new Dictionary<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();
}
Follwoign Java Script funtion which, I am calling on the click event of the button calls the c# method it first name and last name as input parametters 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)
{
return false;
}
else
{
$.ajax({
type:”POST”,
url:”/Admin/SDUsers.aspx/findUsersAjax“,
data:”{firstName:’”+firstName+”‘,lastName:’”+lastName+”‘}”,
contentType:”application/json; charset=utf-8″,
dataType:”jsondata”,
success:function(response)
{ if (response.length<=4) {
$(“#divAjax”).hide(“fast”);
}
else {
var myObject= eval(“(“+ eval( response) + “)”);
BuildTable(myObject);
$(“#divAjax”).show(“fast”);
}
},
error: function (response){
alert(response.status + ‘ ‘ + response.statusText);
}
});
}
}
Struggle point: I was returning Restuls in Json but javascript eval function was not working for me and it took few hours to resolve the issue thanks to http://www.javascriptkata.com/2007/05/08/how-to-use-json/#comment-710
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 thsi way It worked for me var myObject= eval(“(“+ eval( response) + “)”);
Followign 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></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 += ‘</tr>’;
table += row;
}
table += ‘</tbody></table>’;
$(‘#divAjax’).html(table);
}
You should read about SQL Injection before you release the code from this article.
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
You can try
var myObject = eval(’(’ + myJSONtext.d + ‘)’);
Even Iam getting the same error. Iam using Firefox. Please help me out.
Prawin
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.
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.