Friday, August 03, 2007

How to use AJAX in DOTNET web applications

How to use AJAX in DOTNET web applications

Overview:

This document is useful for creating web application using AJAX. This document explain what is Ajax, how to use with sample source code in C#.net.

This document covers the following

1) How to create web application using Ajax
2) How to call server side method from JavaScript
3) How to fetch data from database without taking client side round trip
4) From where to download AJAX framework

Introduction:

ASP.NET AJAX is a framework for creating a new generation of more efficient, more interactive and highly-personalized Web application that work across most of browsers.
What you can do with ASP.NET AJAX:

ü Access remote services and data directly from the browser without writing complicated script.
ü Create next-generation interfaces with reusable AJAX components.
ü Enhance existing Web pages using powerful AJAX controls. Continue using Visual Studio 2005.

Download center

You can download AJAX framework from http://asp.net/ajax/downloads/default.aspx

Sample Source code


In the Web application if we want to get data from the server we have to do server trip to execute code behind function that execute stored procedure/query to fetch/delete/update the data from the database.

server trip is always very heavy operation in the web application. Now using Ajax we can avoid client side server trip and without client side server trip we can get the data in the client side.

AJAX is nothing like magic; it is a way to call server side methods from JavaScript.
Ajax.NET is good for lightweight remote calls using JavaScript.

Let say you have a requirement where if you type any text in the text box corresponding data should display in the table, this is kind of searching related data as when you type any text in the text box.

Below I am giving one example code "How to fetch data from database using AJAX call"

Follow the steps to create Web Application


1) Create one Aspx page name "GetUser.aspx"

a) Create one private method in this page say "GetUsernameListFromDB"
private void GetUsernameListFromDB()
{
string conn = "Data Source= DBServer;Initial Catalog=DBNAme;
User Id= UID;Password= PWD";
//Get the request query
string whereCondition = Request["Condition"].ToString();
string sqlQuery = "select FName,Lname,DOB from Employee
where FName like '" + whereCondition + "%'";
DataSet ds = new DataSet();
ds = SqlHelper.ExecuteDataset(conn,CommandType.Text, sqlQuery);
StringBuilder strXml = new StringBuilder();
strXml.Append("<table border='1' width='100%'
height='100%' cellpadding='2' cellspacing='2'>");
strXml.Append("<tr bgcolor='skyblue'>
<td>First Name </td><td>Last Name</td>
<td>Date of Birth</td></tr>");
//Create Html Table runtime
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
strXml.Append("<tr>");
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
strXml.Append("<td>" + ds.Tables[0].Rows[i][j].
ToString() + "</td>");
}
strXml.Append("</tr>");
}
strXml.Append("</table>");
// This is for to retain the value when page get referesh
Session["XMLData"] = strXml;
//write response data in the page
Response.Write(strXml);
}

b) Call above method in the page load event of "GetUser.aspx.cs" page


protected void Page_Load(object sender, EventArgs e)
{
GetUsernameListFromDB();
}

2) Create another Aspx page name "Default.aspx"

a) Screen shot


b) Design Source code


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">
<title>Getting Data from Database using AJAX Call</title>
</head>

<script>

var xmlHttp;
var requestURL = 'http://localhost/AjaxExample/GetUser.aspx?Condition=';
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0;
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0;
var is_opera
= ((navigator.userAgent.indexOf("Opera6")!=-1)
(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0;
//netscape, safari, mozilla behave the same???
var is_netscape
=(navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0;


function Display_Data(strName)
{
if (strName.length > 0)
{
//Append the name to search for to the requestURL
var url = requestURL + strName;
//Create the xmlHttp object to use in the request //stateChangeHandler will fire when the state has changed, i.e. data is received back
// This is non-blocking (asynchronous)
xmlHttp = GetXmlHttpObject(stateChangeHandler);
//Send the xmlHttp get to the specified url
xmlHttp_Get(xmlHttp, url);
}
else
{
//Textbox blanked out, clear the results
document.getElementById('RelatedDataList').innerHTML = '';
}
}

//stateChangeHandler will fire when the state has changed, i.e. data is received back, This is non-blocking (asynchronous)
function stateChangeHandler()
{
//readyState of 4 or 'complete' represents that data has been returned
if (xmlHttp.readyState == 4 xmlHttp.readyState == 'complete')
{

//Gather the results from the callback
var str = xmlHttp.responseText;
//alert(str);
//Populate the innerHTML of the div with the results
if (document.getElementById)
{
//This indirecting writing into the panel require for IE
var t = document.createElement('div');
t.innerHTML = str;
document.getElementById('RelatedDataList').innerHTML = "";
document.getElementById('RelatedDataList').appendChild(t);
}
else if (document.all)
{
document.all['RelatedDataList'].innerHTML = xmlHttp.responseText;
}
else if (document.layers)
{
document.layers['RelatedDataList'].innerHTML = xmlHttp.responseText;
}
}
}

// XMLHttp send GET request
function xmlHttp_Get(xmlhttp, url)
{
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}
function GetXmlHttpObject(handler)
{
var objXmlHttp = null;
//Holds the local xmlHTTP object instance
//Depending on the browser, try to create the xmlHttp object
if (is_ie)
{
//The object to create depends on version of IE
//If it isn't ie5, then default to the Msxml2.XMLHTTP object
var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP';
// create the object
try{
objXmlHttp = new ActiveXObject(strObjName);
objXmlHttp.onreadystatechange = handler;
}
catch(e){
//Object creation errored
alert('IE detected, but object could not be created. Verify that
active scripting and activeX controls are enabled');
return;
}
}
else if (is_opera)
{
//Opera has some issues with xmlHttp object functionality
alert('Opera detected. The page may not behave as expected.');
return;
}
else
{
// Mozilla Netscape Safari
objXmlHttp = new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}
//Return the instantiated object
return objXmlHttp;
}

function UseValue(strVal)
{
document.frmDefault.txtName.value = strVal;
}

</script>
<body>
<form name="frmDefault" id="Form1" runat="server">
<table border="0" cellpadding="4" cellspacing="0" id="Table2" >
<tr>
<td width="100">Name:</td>
<td>
<input type="text" name="txtName" id="txtName" autocomplete="off" onkeyup="Display_Data(txtName.value);">
</td>
</tr>
<tr>
<td width="100" valign="top">Related Data:</td>
<td>
<div id="RelatedDataList" runat="server"></div>
</td>
</tr>
</table>
</form>
</body>
</html>

c) Code behind (Default.aspx.cs)

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// This require when you need to persist the data after referesh
if (Session["XMLData"] != null)
{
RelatedDataList.InnerHtml = Session["XMLData"].ToString();
}

}
}

d) Run the application and type some text in the "Name" text box




As when you type any text in the "Name" text box without getting server trip for client it display filter data in to the screen.

How this page works internally

1) When you type any text into the textbox onkeyup events of textbox calls JavaScript function "Display_Data(txtName.value);" This function internally points to "GetUser.aspx" page in the form of http module 'http://localhost/AjaxExample/GetUser.aspx?Condition ='

2) And based on QueryString parameter "GetUser.aspx" page_Load calls perticular method "GetUsernameListFromDB()", This method take the parameter and get the data from database and generate html table structure on server side and return (html) result to page using "Response.write(strXml)"

3) Yes, It does server trip but it's happen parallel in server side it's not visible to client page, client page does not refresh in this whole process that why we can say without client side post back we can call code behind method using AJAX.

Limitations

Ø Input from devices such as microphones, webcams, and gamepads; output to devices like printers and portable gadgets.
Ø Playing music and sound effects.
Ø Adding buttons, toolbars, bookmarks, icons; changing browser behavior.
Ø Reading and writing files on the user's hard drive.
Ø Catching events such as shutdown initiation; changing preferences; popping up alerts; reading hardware information.
Ø Providing a full range of keyboard shortcuts while avoiding conflicts with the browser's own keyboard shortcuts.

13 comments:

Unknown said...

Thanks to give help on New topic,The way to guide is realy nice .

Jai said...

Jai,
Notes was very good and simple for a beginner to understand

Anonymous said...

[url=http://www.acheter-viagra.freehostp.com][img]http://www.viagra-achetez.enjoymeds.biz/achat-cialis.jpg[/img][/url][url=http://www.acheter-viagra.freehostp.com][img]http://www.viagra-achetez.enjoymeds.biz/achat-viagra.jpg[/img][/url][url=http://www.acheter-viagra.freehostp.com][img]http://www.viagra-achetez.enjoymeds.biz/achat-levitra.jpg[/img][/url]
[b]cialis[/b]
[url=http://www.mmagame.com/forum/viewtopic.php?t=365]En Ligne PHARMACIE[/url] - cialis generique
[b]Tadalafil 10mg Achat[/b]
http://crhsesaprn.hqforums.com/vp23.html
[b]Cialic Acheter[/b]
[url=http://hefeiexpat.com/forum/index.php?topic=383.0]tadalafil generique[/url] - ACHAT CIALIS GENERIQUE EN FRANCE
[b]cialis generique[/b]
http://www.700musers.com/phpBB2/viewtopic.php?t=588
[b]Tadalafil 10mg Achat[/b]
[url=http://www.lookupamerica.com/board/index.php?showtopic=1666]CIALIS GENERIQUE ACHAT[/url] - achat tadalafil
[b]CIALIS ACHAT EN LIGNE[/b]
[b]achat tadalafil[/b]
[url=http://www.proton-tm.com/board/viewtopic.php?p=1679]ACHAT CIALIS EN LIGNE[/url] - Sialis
[b]vente cialis[/b]
[b]acheter cialis[/b]
[url=http://hellskitchenonline.com/phpBB3/viewtopic.php?f=3&p=28968]Achat Tadalafil 20mg[/url] - Achat Tadalafil 20mg
[b]ACHAT CIALIS EN PARIS[/b]

Anonymous said...

free lesbian no sign up porn drunk lesbians hook up hot college lesbian girl webcams hardcore black on white lesbians black dahlia lesbian bbw lesbian lust gay and lesbian personals

Anonymous said...

And if I already pay for Internet on my phone does it cost any extra on the Iphone?



________________
[url=http://unlockiphone22.com]unlock iphone[/url]

Anonymous said...

http://www.djmal.net/thaspot/members/viagrakaufend
[b]VIAGRA Rezeptfrei PREISVERGLECH VIAGRA BILLIG[/b]
http://www.serataanime.it/forum2/member.php?u=336
[b]VIAGRA Apotheke VIAGRA BILLIG PREISVERGLECH BESTELLEN[/b]
VIAGRA BESTELLEN eur 0.85 Pro Pille >> Klicken Sie Hier << BESTELLEN BILLIG VIAGRA CIALIS VIAGRA Apotheke BILLIG VIAGRA BESTELLEN
http://www.sembrasil.com.br/assets/snippets/forum/viewtopic.php?t=145
[b]PFIZER VIAGRA VIAGRA BESTELLEN[/b]
[url=http://www.einvestorhelp.com/member.php?u=37776]VIAGRA Holland[/url] - VIAGRA BESTELLEN
[b]VIAGRA Schweiz BESTELLEN REZEPTFREI VIAGRA[/b]
[b]VIAGRA ohne rezept VIAGRA BILLIG BESTELLEN[/b]
[url=http://www.postyouradforfree.com/showthread.php?p=313013]VIAGRA erection[/url] - VIAGRA versand
[b]VIAGRA rezeptfrei VIAGRA PREISVERGLECH[/b]
[b]VIAGRA versand REZEPTFREI VIAGRA[/b]
[b]VIAGRA® kaufen
VIAGRA Deutschland
VIAGRA online kaufen
VIAGRA on line
VIAGRA alternativ
VIAGRA rezeptfrei
VIAGRA Kaufen
VIAGRA Apotheke[/b]

Anonymous said...

http://www.insubuy.com/forum/member.php?u=125026
[b]CIALIS KAUFEN EUR 1.10 pro pille >>> Jetzt Kaufen! <<< CIALIS KAUFEN alternativ zu CIALIS[/b]
[b]CIALIS KAUFEN KAUF CIALIS CIALIS alternatives[/b]
http://www.ewheatgrass.com/wheatgrassjuice/members/cialiskaufen.html
Tadalafil, angeboten unter dem Namen Cialis, ist eine neue Gruppe von Medikationen, welche adaquate sexuelle Stimulation erlaubt, die Blutgefa?e des Penis entspannt und der Erektion hilft. Die empfohlene Dosis von Tadalafil betragt 20mg.
Cialis ist das einzige Medikament, welches nicht nur schnell wirkt (wirkt in 30 Minuten) sondern auch bis zu 36 Stunden effektiv bleibt, das Ihnen ermoglicht den richtigen Moment fur Sie und ihren Partner zu wahlen. Sie konnen Cialis am Morgen einnehmen und Sie sind bereit fur den richtigen Moment wahrend des Tages, Abends oder auch wahrend des nachsten Tages. Millionen Manner wurden von der effektiven Wirkung in Milde und von der gema?igten oder harten erektile Dysfunktion von Cialis uberzeugt.
[url=http://www.freshwap.net/forums/members/cialiskaufen.html]CIALIS OHNE REZEPT BESTELLEN[/url] - CIALIS OHNE REZEPT
[b]CIALIS KAUFEN CIALIS OHNE REZEPT FREE CIALIS[/b]
[url=http://www.uhaveaudio.com/forums/member.php?u=185]REZEPTFREI KAUF CIALIS[/url] - CIALIS REZEPTFREI KAUFEN
[b]CIALIS KAUFEN CIALIS BILLIG KAUFEN ONLINE CIALIS prices[/b]
[url=http://www.forexindo.com/forum/members/cialiskaufen.html]REZEPTFREI CIALIS KAUF[/url] - CIALIS im Internet Kaufen BILLIG
[b]CIALIS KAUFEN PREISVERGLEICH CIALIS CIALIS bestellen[/b]

Anonymous said...

[url=http://www.service-dating.com]service dating[/url]

Anonymous said...

[b]proscar and flomax together
[/b]
avandia vs actos
buy actos
how to compound sumycin syrup
what is strattera
asacol causing kidney damage
actos news
imaginext trial pack
premarin vs estradio
albuterol sulfate api
cipro for abcess
aggrenox fish oil
inderal and thyroid storm
order soma online
metformin glucophage for weight loss
generic aldactone
singulair 10mg
aceon overdose
accupril 20 mg
lexapro without a prescription
brevail instead of arimidex
levaquin 500mg
albuterol sulfate in hospice patients
buy ultram 50mg
premarin 0.625 mg
is flomax good for prostatitis
aciphex 20 mg
albuterol sulfate dosage
taking amoxil with cipro
take aldactone and potassium medicine together
buy kamagra in the uk

[url=http://length-of.aragornik.com/chanthece.html] tramadol pain killer [/url]
[url=http://buy-cialis.aragornik.com/ysaccuchrtse.html] cialis and vigra together [/url]
[url=http://genuine-cialis.metlama.bee.pl/vithimerap.html] fast delivery cialis [/url]
[url=http://abilify.andanterra.orge.pl/jenedllyovez.html] drug schedule for aceon [/url]
[url=http://how-is.metlama.bee.pl/lddststolea.html] pamelor 25mg [/url]
[url=http://renagel-product.kaliziare.name/melef.html] requip pills [/url]
[url=http://pamelor-migraine.faramirik.net/kiout.html] prescribed nexium 40 pepcid 20 [/url]
[url=http://phenelzine-kemad.kaliziare.name/quzerach.html] lamictal withdrawal [/url]
[url=http://evista-dia.frodiog.info/netedene.html] company eli evista lilly [/url]
[url=http://evista-cole.aragornik.com/sthespothe.html] evista delco sum [/url]
[url=http://clomid-light.faramirik.net/urlerk.html] clomid injectibles [/url]
[url=http://triglyceride.andanterra.orge.pl/uparesa.html] lopressor 50 mg [/url]
[url=http://abilify.andanterra.orge.pl/serodimat.html] pravachol hyzaar actos aceon [/url]
[url=http://clomid-breast.aragornik.com/pongutom.html] clomid message board [/url]
[url=http://congestive-hea.lamazerro.345.pl/piodonatheai.html] april cope and adalat [/url]

microzide patent number
pdr6 trial pack exe
psa proscar
allegra d 12-hour
amaryl tabs
allegra d canada
will levaquin cure strep
adoxa doxycycline
bruxelles kamagra
desyrel bristol-myers
levaquin prescription drug
how does lasix work
metronidazole flagyl treatment instruction
drug schedule for aceon
singulair 10mg tabs
diflucan dosage
actoplus met generic
abilify linked to pathological gambling
aciphex weight loss and gain
ultram information

http://omeprazole-dos.lamazerro.345.pl/index.html pdr pepcid
[url=http://buy-acomplia.metlama.bee.pl/index.html]acomplia online[/url]
evista information special
[url=http://prograf-blindnes.kaliziare.name/index.html]prograf by[/url]
http://signs-of.bueaga.bij.pl/index.html success rates of clomid
paxil shortage
http://are-naproxen.andanterra.orge.pl/index.html can i give my dog aleve
how is avolox different from omnicef
http://buy-proscar.aragornik.com/map.html |cheap proscar online
[url=http://dog-reg.pirinka.osa.pl/index.html]financial averages apri 2007[/url]

generic altace patent
artane interactions
ordering accutane online reliable
alesse stopped now bleeding
amoxil 875mg
ordering ultram
singulair 10mg tabs
nexium generic
lexapro
proscar false psa

Anonymous said...

http://www.mensstyleforum.com/viewtopic.php?f=3&t=3042
[b]CIALIS KAUFEN EUR 1.10 pro pille >>> Jetzt Kaufen! <<< BESTELLEN REZEPTFREI CIALIS CIALIS erection[/b]
[b]CIALIS KAUFEN CIALIS CIALIS alternatives[/b]
http://www.americanredhots.com/index.php?topic=702.0
[u][b]CIALIS ONLINE KAUFEN OHNE REZEPT[/b][/u]
[url=http://rainedrop.com/community/viewtopic.php?f=2&t=126]BILLIG CIALIS BESTELLEN[/url] - REZEPTFREI CIALIS KAUFEN
[b]CIALIS KAUFEN CIALIS KAUFEN CIALIS erection[/b]
[url=http://www.colleges.ch/curriculum-vitae-f7/kaufen-cialis-eur-1-15-pro-pille-cialis-bestellen-rezeptfrei-t597.html]KAUFEN Preiswertester CIALIS[/url] - CIALIS BILLIG
[b]CIALIS KAUFEN REZEPTFREI KAUF CIALIS CIALIS® kaufen[/b]
[url=http://www.clinicdiy.com/netclinic/modules.php?name=Forums&file=viewtopic&t=50&start=0&postdays=0&postorder=asc&highlight=]Kaufen CIALIS Ohne Vorschrift[/url] - CIALIS im Internet BESTELLEN
[b]CIALIS KAUFEN Kaufen CIALIS Ohne Vorschrift CIALIS information[/b]

Anonymous said...

[url=http://edhbn3td.100webspace.net/warning-fc/ltharishe.html] warts and zantac [/url] [url=http://q0ik6mxq.100webspace.net/side-eff5d/ceanthe.html] side effects with depakote [/url] [url=http://7rv1quwp.100webspace.net/lamictald4/vasphaniona.html] lamisil at athletes foot [/url] [url=http://q0ik6mxq.100webspace.net/side-eff5d/youtsa.html] side effects ultram [/url] [url=http://w8dcb1lk.100webspace.net/experiene7/drsely.html] extended release paxil [/url] [url=http://724krm7o.100webspace.net/what-is-e2/jofreriounth.html] what is the medicine protonix for [/url] [url=http://edhbn3td.100webspace.net/o-brien-af/muluntheng.html] off prozac weaning [/url] [url=http://tbjmyqp6.100webspace.net/norvasc-2e/gezdirdouto.html] norvasc versus benicar [/url] [url=http://f3uc3pra.100webspace.net/wellbutre3/quransality.html] what does cialis look like [/url] [url=http://q0ik6mxq.100webspace.net/risks-of33/vezdig.html] risperdal adverse effects [/url] [url=http://q0ik6mxq.100webspace.net/the-drugfe/ctearioz.html] too much synthroid and fertility [/url] [url=http://452ljkt9.100webspace.net/is-there50/foriethe.html] itching and plavix [/url] [url=http://tbjmyqp6.100webspace.net/paxil-dr5b/chiskeclyo.html] paxil no weight gain [/url] [url=http://w8dcb1lk.100webspace.net/kamagra-d5/udeded.html] kamagra oral jelly for women [/url] [url=http://ztf3xizc.100webspace.net/generic-7e/veemarndy.html] generic viagra now [/url]

Anonymous said...

[center][url=http://www.viagra-billig.medsjoy.biz][img]http://www.viagrakaufen.enjoymeds.biz/kaufen_cialis.jpg[/img][/url][url=http://www.viagra-billig.medsjoy.biz][img]http://www.viagrakaufen.enjoymeds.biz/kaufen_levitra.jpg[/img][/url][url=http://www.viagra-billig.medsjoy.biz][img]http://www.viagrakaufen.enjoymeds.biz/kaufen_viagra.jpg[/img][/url][/center]
[b]CIALIS KAUFEN EUR 1.10 pro pille >>> Jetzt Kaufen! <<< CIALIS OHNE REZEPT KAUFEN CIALIS fuer frau[/b]
[b]CIALIS KAUFEN KAUFEN Preiswerter CIALIS PFIZER CIALIS[/b]
http://www.kanarenforum.de/members/billigcialis.html
[u][b]KAUFEN CIALIS OHNE REZEPT[/b][/u]
[url=http://www.immobilienforum.de/members/billigcialis.html]CIALIS BILLIG[/url] - BESTELLEN CIALIS im Internet
[b]CIALIS KAUFEN CIALIS CIALIS fuer frau[/b]
[url=http://www.naturforum.de/members/billigcialis.html]Pr - CIALIS BILLIG KAUFEN ONLINE
eiswerter CIALIS[/url] - CIALIS Online Bestellen
[b]CIALIS KAUFEN BILLIG CIALIS BESTELLEN CIALIS bestellen[/b]
[url=http://my.prostreetonline.com/member/CialisKaufen]BESTELLEN CIALIS[/url] - CIALIS OHNE REZEPT
[b]CIALIS KAUFEN CIALIS OHNE REZEPT CIALIS rezeptfrei[/b]

Anonymous said...

Hi, here you can get a discount coupon for ALL DRUGS:
order cheap Generic Imitrex generic

order Imitrex in Boston

order Desyrel in Cyprus

buy Aristocort in Tennessee

where can i buy AyurSlim

buy Sublingual Viagra in New Mexico

buy cheap Metoclopramide Metoclopramide fast

order AyurSlim custom hrt

order Lasuna in Nashville-Davidson

Menopause Gum without prescription shipped overnight express

Lisinopril delivery order

order Astelin overnight

Zerit ups delivery only

order Risperdal in Missouri

Ilosone prices

order Relafen in New Jersey

order bulk Augmentin

purchase Trimox in Dover

order Seroquel in Oklahoma

order Lamisil in Glasgow

buy Betapace discount

order canada Aciphex

buy Wellbutrin SR australia

Sinequan purchase without prescription

Tenormin mexico

order Naprosyn in Montgomery

Dulcolax for sale with no prescription required

buy Dostinex cheap us pharmacy

buy Grifulvin V in Columbus

Viagra Soft Flavoured buy Viagra Soft Flavoured