Tutorial: Introduction to AJAX in ASP.NET 2.0 and C#


Server Intellect


Tutorial: Introduction to AJAX in ASP.NET 2.0 and C#

New to AJAX? This tutorial will show you the basics, and how to create an AJAX-Enabled web application. If you are using Visual Studio.NET 2005, you can download the AJAX Extensions from the Microsoft website, which makes it easier to implement AJAX.

AJAX, short for Asynchronous JavaScript And XML, isn't a technology but rather a grouping of technologies. AJAX uses a communication technology (typically SOAP and XML) to send and receive an asynchronous request/response to the server, and then leverages presentation technologies (JavaScript, DOM, HTML, and CSS) to process the response. Applications using AJAX are legitimate today, because most browsers support the necessary technology.

Try Server Intellect for Windows Server Hosting. Quality and Quantity!

The first thing we need to do is to import the AJAX namespace from Ajax.DLL.The Ajax namespace contains Ajax.dll encapsule Asynchronous Javascript and XML in Bin folder. This is a combination of Javascript and XML. The data is transfered in the form of XML.

using Ajax;
using System.Data.SqlClient;

I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.

In this tutorial, the only configuration step beyond that is to add the following code in the web.config file, inside the <system.web> element.

<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
</httpHandlers>

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

In order to make server-side functions available through JavaScript, two things must be done. First, the function or functions in question must be marked with the Ajax.AjaxMethodAttribute. Second, the class containing these functions must be registered through a call to Ajax.Utility.RegisterTypeForAjax during the page load event. Then we use GetData() even of btnGetData and display() event of DropDownList  to do the work.  The button btnGetData is a html button. It display employee data without page post-back. When chose a particular record in the Dropdownlist, the employee name and employee ID will be displayed in the label.

The code below can go in the <head> tags of the ASPX page:

<script language="javascript" type="text/javascript">
function GetData()
{
var response;
Ajax_CSharp.GetData(GetData_CallBack);
}

function GetData_CallBack(response)
{
var response=response.value;

if(response=="Empty")
{
alert("No Record Found !!!");
}
else if(response=='Error')
{
alert("An Error occured in accessing the DataBase !!!");
}
else
{
var arr=response.split("~");
var empID=arr[0].split(",");
var empName=arr[1].split(",");

document.getElementById('dlistEmployee').length=0;
for(var i=0;i<empID.length;i++)
{
var o = document.createElement("option");
o.value = empID[i];
o.text = empName[i];
document.getElementById('dlistEmployee').add(o);
}
}
}

function display()
{
var selIndex=document.getElementById("dlistEmployee").selectedIndex;
var empName=document.getElementById("dlistEmployee").options(selIndex).text;
var empID=document.getElementById("dlistEmployee").options(selIndex).value;

document.getElementById("lblResult").innerHTML="You have selected " + empName + " ( ID : " + empID + " )";
}
</script>

Register Ajax in PageLoad and get data from the employee table of Database.

protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(Ajax_CSharp));
}

[Ajax.AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public string GetData()
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["conn"]);
SqlCommand cmd = new SqlCommand("SELECT * FROM employee", con);
cmd.Connection.Open();

SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet("DataSet");
adapter.Fill(ds, "Table");

if ((ds.Tables[0].Rows.Count <= 0))
{
return "Empty";
}
else
{
string empID = "";
string empName = "";
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
empID += ds.Tables[0].Rows[i][0].ToString() + ",";
empName += ds.Tables[0].Rows[i][1].ToString() + ",";
}
empID = empID.Substring(0, empID.Length - 1);
empName = empName.Substring(0, empName.Length - 1);

return empID + "~" + empName;
}
}
catch
{
return "Error";
}
}

Yes, it is possible to find a good web host. Sometimes it takes a while. After trying several, we went with Server Intellect and have been very happy. They are the most professional, customer service friendly and technically knowledgeable host we've found so far.

The front end AjaxDataSearchCSharp.aspx page looks something like this:

<div align="center">
<input id="btnGetData" onclick="GetData();" type="button" value="To Get Employee Data From DB" style="width: 203px" />
&nbsp;&nbsp;
<asp:DropDownList ID="dlistEmployee" runat="server" onchange="display();">
</asp:DropDownList><asp:Label ID="lblResult" runat="server" Text="No Record Selected"></asp:Label>
</div>

If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!

The flow for the code behind page is as follows.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ajax;

public partial class Ajax_CSharp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(Ajax_CSharp));
}

[Ajax.AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public string GetData()
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["conn"]);
SqlCommand cmd = new SqlCommand("SELECT * FROM employee", con);
cmd.Connection.Open();

SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet("DataSet");
adapter.Fill(ds, "Table");

if ((ds.Tables[0].Rows.Count <= 0))
{
return "Empty";
}
else
{
string empID = "";
string empName = "";
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
empID += ds.Tables[0].Rows[i][0].ToString() + ",";
empName += ds.Tables[0].Rows[i][1].ToString() + ",";
}
empID = empID.Substring(0, empID.Length - 1);
empName = empName.Substring(0, empName.Length - 1);

return empID + "~" + empName;
}
}
catch
{
return "Error";
}
}
}

Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!
 


Comments
umesh pandit said:

Good Tutorial for begineer.

Posted Oct 2, 2008 4:39 AM
Thakkudu said:

its a nice tutorial

Posted Apr 18, 2009 4:51 AM
Yash said:

Simple and easy to understand. Concise. Good Tutorial!!

Posted May 16, 2009 1:05 AM
kumar said:

I used ASP.NET AJAX in Visual Studio 2008. and it was really nice experience to use it with ease.thanks http://www.planetsourcecode.in

Posted May 29, 2009 11:42 AM
Rajneesh Rana said:

Thanks for the tutorial.

Posted Jul 19, 2009 4:56 PM
Reader said:

Nice tutorial, but text advertisements of Severs Intellect every second paragraph are very annoying.

Posted Aug 12, 2009 4:24 AM

Leave a Comment