Академический Документы
Профессиональный Документы
Культура Документы
NET (Part 1)
Introduction
ASP.NET page processing model is post back based. That means in order to
handle any server side event you must post the form back to the server. This
event driven model is certainly powerful and rich but it has drawbacks of its
own. Now a days many browsers support client side JavaScript and DHTML.
AJAX model is all about making intelligent use of browser's capabilities to give
better user experience. In Part 1 of this series I will explain what AJAX is with a
simple example.
What is AJAX?
AJAX stands for Asynchronous JavaScript And XML. AJAX by no way is a new
technology. The parts of AJAX i.e. HTML, XML, DOM, XMLHTTP and JavaScript
are being used for years. AJAX refers to use of these individual pieces together.
Imagine a web form with a TextBox, a Label and a Button. The TextBox is
supposed to accept a CustomerID and on the click of the button you are
supposed to retrieve the total orders placed by the customer and display in the
Label. How will you do it in normal way?
You will write Click event handler for the Button and inside the event handler
you will write all the code to retrieve the total orders depending on the
CustomerID specified in the TextBox. That means for each and every
CustomerID you will cause a post back to the server. Think what will happen if
your page contains lots of other controls or heavy images. Naturally the overall
network traffic will be much more resulting in a poor performance.
AJAX can solve such problems. Using AJAX you don't cause frequent post backs
to the server. Instead you give requests to server side resources (web forms for
example) from the client browser itself. Once the request returns the data you
update the controls accordingly.
On one hand AJAX can give much better user experience and performance but
on the other hand you also need to worry about things such as browsers not
supporting JavaScript and cross browser JavaScript.
Simple Example
To get a feel of how AJAX works we are going to develop a simple example. Our
example consists of two web forms. One will have a Button and a Label. This
web form will call the other web form via AJAX. The other web form will not
have any UI as it is not directly displayed to the user. It will simply return a
string "hello world" in it's Page_Load method. This string is displayed in the
previous form when user clicks on the Button.
• Create a new Web Application in VS.NET
• We then set Label's text to date time stamp. This value will never be
displayed because in AJAX model post back is not happening. We are
putting this code just to prove this point.
• In the .aspx file add following JavaScript function to the <HEAD> section
of the page
var obj;
function GetDataViaAJAX()
{
try
{
obj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e1)
{
obj = null;
}
}
if(obj!=null)
{
obj.onreadystatechange = ProcessResponse;
obj.open("GET",
"http://localhost/AJAXDemo/helloworld.aspx", true);
obj.send(null);
}
return false;
}
• Here, we created an instance of XMLHTTP class. This class is the key to
the overall AJAX model. It is this class that makes asynchronous requests
to the server resources. This class is a part of MSXML parser that ships
with IE.
• We then call open() method of XMLHTTP and pass the request type (GET
or POST), the url to be accessed and whether the request is to processed
asynchronously or no.
• We further check the status code of the request. Status code of 200
indicates ok.
• Set the AJAXMain.aspx as the startup page and run the application.
• Click on the button and you should see a message box with "hello world".
Notice that this is happening without any post back.
Code Download
The complete source code of above sample is available for download along with
the article. Please see top of the article for download link.
Summary
In this article we saw what AJAX is and how it can help you build more
responsive and performance rich web applications. We also saw how to use
XMLHTTP component that ships with IE. In the next article I will show you how
to deal with bit complex requirement tat includes XML data.
• We also attach a client side event handler for "onchange" event of the
DropDownList with GetDataViaAJAX() function.
• In the .aspx file add following JavaScript function to the <HEAD> section
of the page
var obj;
function GetDataViaAJAX()
{
try
{
obj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e1)
{
obj = null;
}
}
if(obj!=null)
{
obj.onreadystatechange = ProcessResponse;
obj.open("GET", "http://localhost/AJAXDemo/datasupplier.aspx?
customerid=" +
document.getElementById("DropDownList1").value, true);
obj.send(null);
}
return false;
}
}
• This function is similar to what we wrote in the previous article.
• Note the part marked in bold. This time we call open() method by
passing the URL of datasupplier.aspx and pass the Customer ID selected
in the DropDOwnList as a query string parameter.
• Now let's write ProcessResponse() function that deals with the returned
data.
• First we remove all the items from the ListBox by iterating through it
and setting individual item to null
• We then iterate through all the elements of this array and add the Order
IDs to the ListBox.
• Finally we send this XML data back to the client using Response.Write()
methiod.
• Set the DataConsumer.aspx as the startup page and run the application.
• Select any Customer from the DropDownList and you should get the
relevant Order IDs.in the ListBox.
Code Download
The complete source code of above sample is available for download along with
the article. Please see top of the article for download link.
Summary
In this article we saw how to work with data from a DataSet. The GetXml()
method of DataSet class comes handy for generating XML version of your data
instead of manually formatting it. In the next article I will show how the values
addeded from client side JavaScript can be accessed on the server.
• Use Request.Form collection directly on the server and get the value
• One that calls the above function when you click on a post back causing
control (SendCustomerID in the example below)
• One that receives the data returned when the call is over
(ReceiveServerData in the example below)
As an example we will develop a web form with a DropDownList and a ListBox.
The DropDownList is filled with CustomerIDs from Customers table of
Northwind database. The ListBox displays the OrderIDs for a selected customer.
Registering the client side functions with the page framework
In order to register the above functions with the page framework you need to
write the following code in the Page_Load event:
ClientScriptManager m = Page.ClientScript;
string str = m.GetCallbackEventReference
(this, "args", "ReceiveServerData",
"'this is context from server'");
string strCallback = "function CallServer(args,context)
{" + str + ";alert(context);}";
Page.ClientScript.RegisterClientScriptBlock
(this.GetType(), "CallServer", strCallback, true);
Here,
• Write it in a .js file and use it in the SRC attribute of SCRIPT tag
if (isValid)
{
var cardNumbersOnly = cardNumber.replace(/ /g,"");
var cardNumberLength = cardNumbersOnly.length;
var lengthIsValid = false;
var prefixIsValid = false;
var prefixRegExp;
switch(cardType)
{
case "MASTERCARD":
lengthIsValid = (cardNumberLength == 16);
prefixRegExp = /^5[1-5]/;
break;
case "VISA":
lengthIsValid = (cardNumberLength == 16
|| cardNumberLength == 13);
prefixRegExp = /^4/;
break;
case "AMERICANEXPRESS":
lengthIsValid = (cardNumberLength == 15);
prefixRegExp = /^3(4|7)/;
break;
default:
prefixRegExp = /^$/;
alert("Card type not found");
}
prefixIsValid = prefixRegExp.test(cardNumbersOnly);
isValid = prefixIsValid && lengthIsValid;
}
if (isValid)
{
var numberProduct;
var numberProductDigitIndex;
var checkSumTotal = 0;
return isValid;
}
We will not discuss this function in detail here but it should be fairly easy to
follow if you have followed the server side code. Note how the parameter val
of this function provides access to the emitted attributes in object based
manner.
That's it. Now, compile the control project and you are ready to use it on any
of your web forms.
Developing a test web form
In order to test the control create a new ASP.NET web application and add a
markup like this to its .aspx file:
<%@ Register TagPrefix="cc1"
Namespace="CreditCardValidatorVB"
Assembly="CreditCardValidatorVB" %>
...
...
<script src="ccvalidation.js"></script>
<cc1:CreditCardValidator
id="CreditCardValidator1"
runat="server"
ErrorMessage="This is error message"
ControlToValidate="TextBox1">
This is error text
</cc1:CreditCardValidator>
Note that I have put the client validation function in a file called
ccvalidation.js. If you set EnableClientScript property to True then the
validation will be performed on the server side else post back will happen and
server side validation will occur. Now run the test web form and see your
control in action!
Summary
Credit card validation is a commonly required on almost all the e-commerce
sites. Using ASP.NET validation control framework you can develop your own
validation control that validates the credit card on client side as well as on the
server side.