Beginning Ajax with ASP.NET- P3

Beginning Ajax with ASP.NET- P3

Beginning Ajax with ASP.NET- P3:Thank you for purchasing Beginning Ajax with ASP.NET. We know that you have a lot of options when
selecting a programming book and are glad that you have chosen ours. We’re sure you will be pleased
with the relevant content and high quality you have come to expect from the Wrox Press line of books.

Nội dung Text: Beginning Ajax with ASP.NET- P3

Chapter 1
What Is Ajax?
So into this development environment comes a set of technologies that are collectively referred to as
Ajax. If you are an “old guy” developer like us, then Ajax represents a similar concept to the client-
server development we mentioned earlier in the chapter. With client-server development, the amount of
data transferred is minimized over a terminal application by transferring only the necessary data back
and forth. Similarly, with Ajax, only the necessary data is transferred back and forth between the client
and the web server. This minimizes the network utilization and processing on the client. Figure 1-3
shows that typically Ajax operates with the assistance of some type of proxy.
Web browser client
Ajax proxy services
Data back in
XML data
an XML format
format in
or other format
over HTTP
without the
with no
weight of a
postback.
postback.
Web server and associated backend
services, such as web services.
Figure 1-3
Advantages of Ajax
The advantages of Ajax over classical web based applications are:
❑ Asynchronous — Ajax allows for the ability to make asynchronous calls to a web server. This
allows the client browser to avoid waiting for all data to arrive before allowing the user to act
once more.
❑ Minimal data transfer — By not performing a full postback and sending all form data to the
server, the network utilization is minimized and quicker operations occur. In sites and locations
with restricted pipes for data transfer, this can greatly improve network performance.
❑ Limited processing on the server — With the fact that only the necessary data is sent to the
server, the server is not required to process all form elements. By sending only the necessary
data, there is limited processing on the server. There is no need to process all form elements,
process the viewstate, send images back to the client, and no need to send a full page back to
the client.
6

Introduction to Ajax on ASP.NET
❑ Responsiveness — Because Ajax applications are asynchronous on the client, they are perceived
to be very responsive.
❑ Context — With a full postback, the user may lose the context of where they are. The user
may be at the bottom of a page, hit the Submit button, and be redirected back to the top of
the page. With Ajax there is no full postback. Clicking the Submit button in an application that
uses Ajax will allow the user to maintain their location. The user state is maintained, and the
user is no longer required to scroll down to the location that he or she was at before clicking
Submit.
Figure 1-4 shows how the user interface can still operate while using Ajax. The UI is not locked during
the server processing.
User Action User Action User Action
Server Response Server Response
Figure 1-4
History of Ajax
For all of its perceived newness and sexiness, the technologies that make up Ajax are really not new.
The ability to communicate back to the server through a hidden frame without posting the main page
back to the server has been around for a long time. Communication between client and server has been
available — back to the release of Internet Explorer’s ability to script ActiveX controls on the client browser
and to the MSXML component, both of which date back into the late 1990s. Personally, I saw the first for-
mal usage of client script and MSXML in 2003. The problem with the technology at that time was the
need to manually create the necessary client-side JavaScript. In 2003, there was too much code overall
that had to be written and too much custom code that had to be written to get this to work. It has been
only in the second half of 2005 that client-side libraries and server-side support for ASP.NET have
started to make their presence felt and been used significantly.
The mainstream development community has only recently started using the technique. The release of
Google’s Suggest and Maps are what really opened the eyes of the users to the development technolo-
gies. These applications sent a shockwave through the development community.
7

Chapter 1
Technologies That Make Up Ajax
Ajax is a general umbrella term. As mentioned earlier, Ajax itself stands for Asynchronous JavaScript
And XML. The term Ajax was actually coined by Jesse James Garret of Adaptive Path in an essay that
was published in February 2005 (www.adaptivepath.com/publications/essays/archives/
000385.php) and was quickly accepted by the development community.
Based on this general umbrella term, take a look at the specific items that make up Ajax:
❑ XmlHttpRequest — XmlHttpRequest allows the browser to communicate to a back-end server.
This object allows the browser to talk to the server without requiring a postback of the entire
web page. With Internet Explorer, this capability is provided by the MSXML ActiveX compo-
nent. With the Mozilla Firefox and other web browsers, this capability is provided by an object
literally called XmlHttpRequest. The XmlHttpRequest object is modeled after the MSXML
component. The client-side JavaScript libraries hide the differences between the various browser
environments. Sometimes these communications are done through a hidden FRAME or IFRAME.
❑ JavaScript — JavaScript provides the capabilities to communicate with the back-end server.
The JavaScript must be version 1.5 or later. Although JavaScript is not specifically required, it
is needed from the standpoint that JavaScript is the only client-side scripting environment sup-
ported across the major modern web browsers. There are other client script languages; however,
these are not supported across all browsers.
❑ DHTML/DOM support — The browser must support the ability to dynamically update form
elements, and the ability to do this in a standard way comes through the support for the
Document Object Model (DOM). By supporting the DOM, it becomes easy for developers to
write a single piece of code that targets multiple browsers.
❑ Data transport with XML or JSON — Using XML allows for the ability to communicate with
the web server in a standard mechanism. There are situations where the JavaScript Object
Notation (JSON) is used as the communication notation instead of straight XML.
Running Ajax Applications
Unfortunately, not all web browsers ever produced will support Ajax. To run Ajax, a web browser must:
❑ Be relatively modern. Ajax style applications are not available in all versions of all web browsers.
Whereas Internet Explorer version 6, Firefox version 1.5, and Opera 8.5 provide support for
these applications, older versions may be problematic because of their support for different
versions of the other requirements.
❑ Support DOM.
❑ Utilize JavaScript.
❑ Support Extensible Markup Language (XML) and Extensible Style Language Transformation
(XSLT).
❑ Possibly have ActiveX enabled on the client. If you are using the Internet Explorer browser
while running on Windows, you may have problems if ActiveX is not enabled.
8

Introduction to Ajax on ASP.NET
Who’s Using Ajax?
Great, now that you have seen that there is this technology called Ajax, are you alone in not having seen
or talked about this before? Absolutely not! Ajax has just recently taken off in the second half of 2005
from a mindshare standpoint. As discussions have gone on with counterparts in the development com-
munity, many developers are just now looking to what Ajax can do for their applications and ultimately
their customers. So, just who is using Ajax publicly?
❑ Google Suggest — Google Suggest features a dynamic drop-down list box that provides possi-
ble items to search on along with the approximate number of search results.
❑ Google Maps — The ability to grab a map and zoom around without requiring a postback is
just amazing. This app/service took the development world by storm when it came out.
❑ Google GMail — Google GMail is a web-based email system available through Google.
❑ Microsoft Hotmail Kahuna update — At the time of this writing, the Hotmail upgrade that
is referred to as Kahuna is in beta test. As a beta user of the application, I can testify to the
improved user interface and responsiveness that this application provides.
❑ Live.com — The local.live.com service from Microsoft is actively using the Atlas framework, as
is nearly the entire Live.com service.
❑ Easy Search component — The ASP.NET Easy Search Component provides support for search-
ing a single web site similar to the Google Suggest service available through Google.
❑ Other component vendors — Component vendors such as ComponentArt, Dart, and others are
providing controls that provide a rich user experience without forcing a full postback.
In addition to third-party interest, the amount of developer interest is tremendous. For example, one
only has to put the word Ajax into a blog title to receive an increase in the number of web views. Given
the amount of third-party support and the interest of developers, it is only a matter of time before every-
one is using it.
Problems Ajax Won’t Solve
Ajax is a great technology with a lot of help for typical application problems and a lot of general
promise. It will help in areas like network load and user context by sending only the necessary data,
creating less network traffic when processing a command. The user is not redirected to the top of a page
when a command is sent the server. The problem is that to successfully run Ajax, a user needs to have
the transport mechanism and JavaScript support mentioned previously. That sounds like something that
any modern browser has, so what’s the problem? Well, the problem is that many mobile browsers have
support for neither. With many of Ajax solutions, you have limited or no downlevel support, so if you
must support a mobile system, you may be limited to writing multiple versions of your application
because Ajax may not be the right technology to include.
9

Chapter 1
Summar y
Ajax provides developers a foundation to build web-based applications that provide an improved user
experience. In this introductory chapter, you have looked at:
❑ Development from a historical perspective
❑ Web development methodologies
❑ Some of the features that Ajax provides, such as improved user responsiveness and decreased
load on the web server
❑ Multiple technologies that can improve the user experience
❑ Ajax, the problems that it solves, and who is using it
In the next chapter, you are going to examine Dynamic HTML (DHTML). Additional chapters will look
at the other technologies that make up Ajax. After that you will examine the Ajax.NET library, Microsoft
Atlas, and finally tips and tricks on debugging client-side applications.
10

2
Introduction to DHTML
Dynamic HTML (DHTML) is a combination of three technologies: Hypertext Markup Language
(HTML), Cascading Style Sheets (CSS), and JavaScript. With these technologies, the content in a
browser becomes dynamic, not having to rely on time-consuming updates from round trips back
to the server. Additionally, finer control over the user experience is available by leveraging the
various events inherent in HTML, such as playing a small sound when the mouse moves over an
image or providing custom context menus instead of the standard one provided by the browser.
This chapter will introduce JavaScript, and then move into how it can interact with the browser
environment to modify the HTML and CSS that make up the web page being displayed. Colors,
images, text, and more can be modified, all through JavaScript code. In the next chapter, the
coverage dives deeper, analyzing the nature of objects and continuing into the Document Object
Model (DOM).
In this chapter, you take a look at:
❑ JavaScript basics
❑ The alert, write, and loop functions
❑ Modifying the status bar
❑ Getting input from the user with the prompt() function
❑ JavaScript events
❑ The document.getElementById() function
❑ The innerHTML property
What JavaScript Is, and What It Isn’t
In the realm of computer languages and programs, there are two major types: compiled and
interpreted.

Chapter 2
❑ Examples of compiled programs are as simple as the Notepad application you’ll be using to edit
the samples shown in this chapter. Notepad was written in C++ and compiled to run specifi-
cally on 32-bit or 64-bit Intel hardware. Therefore, it is very specific as to what platform can run
the code.
❑ JavaScript on the other hand is interpreted, meaning that any platform capable of interpreting the
code can run it. For our purposes, this will mean virtually any web browser, from small handheld
devices like web-enabled phones up to browsers available for mainstream operating systems
like Internet Explorer, Opera, Safari, and Firefox. Some languages, such as .NET and Java, are
actually hybrids, being both partially compiled and partially interpreted.
Although it’s tempting to think that JavaScript is closely related to Java, because of its name, surpris-
ingly that is not the case. The only real similarities between the two are that the structure of the code
looks very similar, with the curly braces and semicolons, and they both provide an object-oriented pro-
gramming experience. Java does this more elegantly and has established itself as a great academic tool to
experiment with object-oriented code design. But the object model is very different from JavaScript.
General Rules of JavaScript
JavaScript code comprises a series of statements. And JavaScript statements are composed of either text
that leads up to a semicolon or text that opens up a code block inside curly braces. Here’s an example of
a couple of statements that first declare a variable called message and then present it on the screen in a
pop-up box:
var message=”Hello, world!”;
alert(message);
The computer determines the end of each of the statement simply by where it finds a semicolon. These two
statements could have been placed on the same line with a semicolon separating them. But it is much
clearer to put them on separate lines.
Most JavaScript interpreters will actually allow statements to exist without the semicolon appearing at
the end of the line. But this is not in keeping with the specifications of other similar languages like Java,
C++, and C#. So, it’s recommended to keep the habit of using semicolons at the end of statements. All of
the JavaScript examples in this book will do so, but when you delve into other samples from the Internet,
you will undoubtedly find JavaScript code that omits the semicolons.
Now take a look at an example of a statement that opens a code block:
if(grade>=90)
{
alert(“You got an A!”);
}
In this sample, the curly braces define a code block, and the single line of code found within runs only if
the grade variable is greater than or equal to 90. There are two statements shown, if and alert, and
there is no concluding semicolon required after the code block. In addition to having code blocks with
an if statement, you’ll see in upcoming samples that they are also found with the looping statement for
and when functions get defined.
12

Introduction to DHTML
Writing Your First Block of JavaScript Code
So, now that you’ve seen JavaScript statements, you can write a few in order to create output in a web
browser. Follow along by opening a copy of Notepad and typing in this sample or simply get all the
code for the book from the download section of http://BeginningAjax.com. This sample is found in
the file chapter_2_starter.htm.
In the example that follows you have a simple web page with some text, and in a element,
one line of JavaScript, an alert statement. You have already seen examples of some simple output oper-
ations using the alert function. The alert function is a method of the window object. The window
object is present as part of every browser’s object model.
Keep in mind that JavaScript code is case-sensitive, so if you do opt to type it all in, then pay particular
attention to getting the casing on all JavaScript lines correct.
Some text before the Javascript
alert(“Hello, world”);
Some text after the Javascript
Save the file as some name of your choosing with an .htm extension, and then when you open it with a
web browser, you should see a pop-up appearing that presents “Hello, world,” as shown in Figure 2-1.
Figure 2-1
13

Chapter 2
The alert() function has produced a basic dialog box for the user to interact with, but as you can see,
the user is allowed to acknowledge the prompt only by clicking the OK button.
If you are using either Internet Explorer 6.0 on a system that has Windows XP Service Pack 2 installed
or Internet Explorer 7.0, then depending on your security settings you will probably be presented with
an information bar explaining that Internet Explorer has restricted the file from showing active content.
Simply click on the bar, select “Allow Blocked Content . . .” and select “Yes.”
Notice that during the time the pop-up is showing, in the background, on the web page, only the line
Some text before the Javascript has been rendered. Then after clicking OK to dismiss the pop-up
text, the rest of the page is shown, and you see the line Some text after the Javascript. So, there
is a sequence of events going on here. Because the JavaScript section was placed within the ele-
ment, it ran as the page was being rendered. You’ll experiment a little more with this kind of JavaScript,
which runs as the page is being rendered, and then move into JavaScript that sits dormant until an
event, such as a button click, has occurred.
There are several places that JavaScript can be placed inside an HTML page. All of the code samples in this
chapter will be placed, as was done in the first sample, within the element. This is the same place
that ASP.NET adds any JavaScript that is established using Page.RegisterClientScriptBlock().
You can also place JavaScript in the element. Another technique, described in the next chapter,
is to place JavaScript in a separate code file, usually named with a .js extension, and then have a
element that includes the code file as if it were merged into the HTML at that point.
document.write()
You can see another way to create output by modifying this sample. Change the function alert to
document.write, so the element looks like this:
document.write(“Hello, world”);
Now the “Hello, world” text is placed right within the rendered page, just as if it was part of the
HTML itself.
Using document.write() in Nested for() Loops
With document.write, you can have the client build calculated or repetitious HTML. As an example,
you can put a few more lines of code in the element to automatically build a 10 × 10 multipli-
cation table:
document.write(‘’);
for(y=1;y

Introduction to DHTML
document.write(“”);
}
document.write(“”);
In this example, you see two for loops, each of which opens a code block and one of which is nested
inside of the other. The innermost document.write(), which builds the elements, is run 100
times and produces the output shown in Figure 2-2.
Figure 2-2
Notice that right after each of the for statements there is a somewhat cryptic set of code in parentheses,
broken into three parts separated by semicolons. These are the parts that make up any for() loop. At
the very least the semicolons need to be present to call out these three pieces, and the table that follows
shows what each part does.
for ( x=1; x

Chapter 2
Single Quotation Marks and Double Quotation Marks in JavaScript
You have seen a couple of samples that use double quotation marks to surround the
strings found in JavaScript. But in this example using those quotation marks would
have confused the browser as to what should actually be included as part of the
onload attribute. The start of a JavaScript string set up with double quotation marks
would have looked to the browser just like the end of that onload attribute.
Fortunately, JavaScript lets you enclose strings with either double quotation marks or
single quotation marks (apostrophes) so that you can work around this issue. So, that’s
exactly what you have done here.
Okay, so if apostrophes mark the start and end of your JavaScript string, what happens
when you want to include an apostrophe as part of the string, such as with the word
It’s in this case? From the sample, you can see that it works if you precede that apos-
trophe with a backslash. This backslash is called an escaping character, which is a great
trick, allowing us to put in double quotation marks and apostrophes wherever we need,
as well as the actual backslash character itself. In a JavaScript string two backslashes in a
row is interpreted as being a single backslash character. This whole business of escaping
is a similar concept to using &lt; in XML or HTML to represent the less than symbol.
You can read more about escaping characters in JavaScript in Chapter 3.
window.status and Events
Another way to present data is with custom text in the status area located at the bottom of the browser
window. If you were to do this in the same element used so far in the chapter, then the text
would be changed very briefly while the page is being rendered but then overwritten by the browser
with the text Done once the page is complete. So, instead you need to find a way to have this next piece
of code run after the page has finished rendering. The perfect place is in something called an event handler
on the tag. There are several events you could trap in this way, and the one you want for this
example is called onload.
You can find more information about event handlers in Chapter 3.
So, for this example, change the tag to look like this:
This way, when the page is rendered, the actual document content is not affected at all; it looks the same.
But once it is all rendered, then in the status area at the bottom of the window you find your custom text,
as shown in Figure 2-3. If your browser is not currently configured to show the status bar, then in both
Internet Explorer and Firefox, you can use View➪Status Bar to turn it on.
Firefox users: In order for this example to work, you must tell Firefox it’s okay for JavaScript to change
the status bar text. This is done from Tools➪Options➪Content➪Enable JavaScript➪Advanced➪
Change status bar text.
16

Introduction to DHTML
Figure 2-3
Examine how this works — when the of the document is fully loaded, the browser sees if any
pieces of code out there care about that occurrence by searching for code that has registered for the
onload event. The change made to the tag was to include an inline event handler, effectively
registering your code to be called when that event fired. So, when the browser finished rendering the
page, this JavaScript code that was found within the double quotation marks was executed:
window.status=’It\’s a beautiful day’;
Getting Input from the User
Now that you’ve seen how to output information in a couple of ways, you need to see how to get some
input with the confirm() and prompt() functions.
The confirm method is used to invoke a confirmation dialog box like this:
if (confirm(“This is a confirmation box”))
alert(“You clicked OK”);
else
alert(“You clicked cancel”);
This produces the traditional OK/Cancel dialog box, as you’ll see later in the chapter. The confirm method
returns a value of true if the user clicks the OK button, and false if the user clicks the Cancel button.
The prompt dialog box is invoked by using the prompt method of the window object. So, suppose you
would like to ask the user what his or her name is and then present that as text in the page. Here is some
code you can put in your element to make that happen:
var name=prompt(“Please enter your name”,””);
document.write(“Welcome “+name);
In this case, you’ve declared a variable called name and assigned it to whatever string comes back from
a pop-up textbox presented to the user. The box starts out blank because of the second parameter being
passed into prompt, which is a blank string. In the next document.write statement, the text entered by
the user is appended to a string in order to present some welcome text. The + operator is not just used
for addition, but in this case, when working with strings, it concatenates one string on the end of another.
You will notice we have not prefixed any of the method calls with the window object such as window
.prompt(“Please enter your name”,””);. This is because the window object is the root, or
default, object within the browser. The alert, confirm, and prompt methods can be inferred to be a
part of the window object, so prefixing the method call with window. is not necessary.
17

Chapter 2
Security Concerns When Getting Text Input
Because the name is written out exactly as it was entered, you want to be very careful when accepting
any assorted text from the user because exactly what someone types in is presented on the screen,
including any additional HTML or JavaScript. Try putting this in when prompted:
location.href=”http://www.wrox.com”;
When the page is rendered, the included script runs as part of the page and redirects the browser to the
Wrox web site! Although we love the Wrox web site, this is probably not at all what you intended when
you asked for the user’s name. So, taking this example further, what if you blindly stored the text from
the user in a database and then on the main page of your site presented a dynamic list of which users are
currently online? When that user is online, suddenly anyone who visits your site is redirected to another
page. This kind of attack is called HTML injection and is related to Cross Site Scripting (XSS). So to avoid
this problem, you need to include code to filter out unintentional HTML elements and JavaScript.
Conveniently, this kind of protection is intrinsic in Microsoft’s ASP.NET environment when using the
.NET Framework 1.1 or later.
Canceling the Normal Outcome of an Event
So, now you can look at another event handler called onclick. Every visible element found on an
HTML page provides this event handler, even the element. So, this really could be placed any-
where. But people are more accustomed to clicking hyperlinks, so for this example you are going to
include this handler on an element that is used to navigate to other pages. What if you wanted to
confirm that people really wanted to navigate to another page when they clicked a link? Add this HTML
at the end of your current content to see how this is done:
Knowledge Base Software
The confirm() function presents a pop-up with both OK and Cancel buttons, as shown in Figure 2-4.
When a choice is made by the user, confirm() will equal true if the user clicks OK, or false if the user
clicks Cancel or closes the pop-up. Returning this true or false in an onclick event handler deter-
mines if the handling of that event should continue or not.
Figure 2-4
18

Introduction to DHTML
The return keyword indicates that you’re done with the piece of code that is running, and you can
return a value back to the caller. So, in this case when someone clicks Cancel, a value of false is
returned and whatever the tag would normally do when clicked is cut short and does not happen.
Hence, clicking Cancel has the effect of bypassing the actual navigation to another page.
There are other event handlers you can defer by returning false, such as the onsubmit event of a .
You can find more information about event handlers in Chapter 3.
Causing an Event Not to “Bubble Up”
There is another concept related to using return false in an event handler. If you fully handle a given
event in a contained control, you may not want that same event to “bubble up” to any parent controls it
is within. For instance in the previous example, you may not want the onclick event on the to be
seen by an onclick handler for the element. But by virtue of being a child element under
, normally this onclick would bubble up. If you use only return false, then it will defer
what would happen on the but not what would happen in an onclick on the . To keep this
from happening, use this statement:
event.cancelBubble=true;
You must use this statement before any return because executing return indicates that you’re done
with the event handler code and want to return control to the browser.
Working with Images
By this point, you’re probably starting to see that JavaScript can be a very handy way to enhance the
user experience. But definitely the best is yet to come. Now you’re going to see some “eye candy” types
of examples, starting with images. You can begin by placing an image on your existing page by adding
this line before the closing tag:
Make sure that you have a folder called images and the GIF files in place before you render this sample.
When referring to the pathing of files on a Windows machine, backslashes are used to delimit each folder
name found in the path. But in UNIX, which is the platform on which the Internet was born and pre-
dominantly accessed, the forward slash is used instead. So, for all web development when providing
pathing in a URL, make sure to use the forward slash.
The JavaScript in the onclick event handler says to bring up a pop-up with the alert statement. And
shown in that pop-up will be whatever this.src is equal to. In event handlers, the keyword this is a
reference to the object that experienced the event, which in this case is the actual image itself. By adding
a dot and additional naming, you can then reference properties or methods of that object, such as src in
this case being the URL from which the image data got loaded. Thus you can render the page and click
the image to see its URL, as shown in Figure 2-5.
19

Chapter 2
Figure 2-5
Working with the image src Attribute
Now what if you wanted to change the image when it is clicked? You can just assign a different URL to
this.src, and it is then updated on the fly. Try that by changing the JavaScript in the event handler so
that it now looks like this:
Now when you click the first time on the image, this is the JavaScript that runs:
this.src= ‘images/ArrowRight.gif’;
Thus, as soon as the new image file loads, it is changed out to present the other arrow image.
The use of the src attribute with the tag is discussed in Chapter 3.
Using Functions
Wouldn’t it be nice to have the two images toggle with each click? How can you do this? It takes a little
more code, and writing very much logic inside the double quotation marks of the onclick attribute
starts to get a little obnoxious. So, this is the perfect point to introduce how to use a function. A function
simply wraps up a bundle of useful code into a code block that can be called by name. In this case, the
onclick code will call into a function called ChangeMe(), which will be defined in the
element.
You haven’t deleted the element that you were using before, have you? Hopefully not! But if
so, then you can simply add one in again. It can exist anywhere in the or elements.
It doesn’t have to exist before the element, since it is called after the page has fully loaded.
Within that element, add this:
20