Using AJAX in ASP.NET Applications

baasopchoppyΑσφάλεια

5 Νοε 2013 (πριν από 4 χρόνια και 2 μέρες)

209 εμφανίσεις

©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

1


Using AJAX in ASP.NET Applications


In this
lesson

you will learn how to create an ASP.NET web application that uses AJAX to manage client
-
server communications.

What does AJAX stand for?
AJAX

is an acronym for
asynchronous JavaScript and XML
. But AJAX is really
a group of interrelated web development techniques. The main difference between ASP and AJAX is that
AJAX technologies are used on the client
-
side to creat
e interactive web applications

and based on cross
-
platform standards.

ASP is a server side technology and platform specific.

Client
-
Server Communication

But let us step

back first at the big picture of how the communication works between the client and th
e
web server.

Traditional Browser Client and Web Server Communication

When the browser sends a request
for a resource such as a web page, it uses HTTP to make

the request
to the web server called the
HTTP Request
. Remember that the browser makes these req
uests using the
HTTP Get and Post methods.
In the beginning, the request was for an html page and the web server
simply
responds by sending

the browser and any related images and style sheets to the client’s browser.
This is known as the
HTTP Response
. Thi
s

request and response communication stops
after the client
receive
s

the web page. This is an example of a request for a static web page

where the content does not
change
. The web server does not keep the communication channel open between the client and t
he
browser.

Browser and Web Server Communication Using Server Side Applications

Likewise, f
or server side programs, the web server does not keep the communication channel open
between the client and the browser. Using the file extension of the web page
requested a

web server
would receive the request. The ASP engine would process the ASP server side code in the file. The code
in the file might be a request to retrieve data from a database, locate content in a file, or even perform a
calculation. The web
server will return a response to the web browser, which includes the html code and
any client side scripts, images or style sheets. The web content in the page can be

considered dynamic
but the communication is still static. As you have learned, the web se
rver can bypass this limitation by
using variety of mechanisms that can be used to identify the client and maintain data across page
requests. These mechanisms include cookies, session va
riables, custom HTTP variables and
QueryStrings.
But each time the pa
ge needs to update the content in the page, a request has to be sent
to the web server, which has to go through the entire process. This process can cause delays in response
time
while the page completely reloads in the browser
and also
cause the web page
to flicker.

©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

2


The benefits of AJAX includes the ability to manage the client
-
server communication, improve response
time and decrease the visual disturbances and flicker when content in the page changes.

Companies like Google have adopted AJAX in order to
improve client responses but also to help improve
the efficiency of the request
-
response communication. Google uses AJAX currently for Google’s
Suggestions in their search engine so that when users enter a term, suggested phrases pop up to help
the user bu
ild their search terms.

Google also uses AJAX for Google Maps and Gmail.

How does this happen?
You learned in previous classes that JavaScript allows you to interact with the
web browser using objects

built
-
into the browser

such as window, document, browser, form and
location.
These are objects within the browsers
document object model

(DOM).
For example, you can
combine the window object and JavaScript to create pop
-
up windows. You can use the form objects to
retrieve data
from form fields and validate the form data before it is sent to the web server. You can
process order forms and perform calculations on the client browser.

Your browser also has an object called
XMLHTTPRequest Object

that can help make asynchronous
prog
r
amming calls to the web server when an event is triggered in the browser.


By allowing these calls to be asynchronous, the web page does not have to
reload the entire web page
for each request. The AJAX layer will make the HTTP Request and receive the resp
onse. The
XMLHTTPRequest object can create the server request and send it to the web server. The web server
receives the request, and sends the response
,

which is received by the XMLHTTPRequest object and
then processes the returned data
,

which is used to
update the web page.

It is important to remember that not all browsers may support the XMLHTTPRequest object and it’s
methods.
Older browsers may have problems such as the browser back button may not work correctly,
the browser may take up significant res
ources by making many requests or the browser may not fully
support the JavaScript library.
Most
new

browsers support AJAX because they support JavaScript and
HTML.

You can create AJAX applications using JavaScript. However, this week you will learn how y
ou can use
the built
-
in controls and tools within ASP to create an AJAX application.

Project Data Files

Open the data files for this lesson.

1.

Open Visual Studio.

2.

Go to File. Then select Open Project. Browse to locate the AJAX.sln file and click Open.



©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

3


Client
-
Server Communication

In this
section

you will learn how to create an ASP.NET web application that uses AJAX to manage client
-
server communications.

Does my software support AJAX?

In
your textbook readings
, the authors discuss the
AJAX Toolkit
.
If
you
are using Visual Studio 2010 or later, you have AJAX support built
-
in.
You can verify this by looking at the
Toolbox.

Simply create an ASP page and then open it. Look at the Toolbox and
you should see a tab called
AJAX Extensions
. As you can see in Figure 1,
the AJAX extension controls

are listed

in the Toolbox, including the
ScriptManager
,
ScriptManagerProxy
,
Timer
,
Upda
tePanel

and
UpdateProgress
.
If you see these controls, you know you have Ajax
installed correctly.

Depending on the version of ASP and Visual Studio .NET, you likely already have
AJAX

installed

but may
not have the Toolkit
.
However, i
f you are using
versi
ons earlier than
Visual Studio .NET 2008 Professional
Service Pack 1

you
may not have support for AJAX
.

When you have AJAX
installed

you will also see other types of AJAX enabled items in the

project
t
emplates. However, you can use AJAX in a basic web for
m, which is what we will do as we start to learn
AJAX!

We’ll cover the Toolkit in one of the later examples.

WebForm1
.aspx
-

Flickering

Let’s look at this example,
WebForm1
.aspx
. In markup view,
look at

the code to display the
animated
image
, label for th
e
current
time and a button. Notice th
e event handler for the button calls the code to
run when the user clicks on the button.

Code Snippet:


<
div
><
img

src
="Images/clock.gif"

/></
div
>



<
br

/><
br

/>


<
div
>



<
asp
:
Label

ID
="lblCurrentTime"

runat
="server"

Font
-
Bold
="True"></
asp
:
Label
>


<
br

/><
br

/>


<
asp
:
Button

ID
="btnUpdateTime"

runat
="server"

Text
="Display Current Time"



onclick
="btnUpdateTime_Click"

/>


</
div
>



<
br

/><
br

/>


<
asp
:
Label

ID
="lblError"

runat
="server"></
asp
:
Label
>




Figure
1

AJAX Extensions

in the Toolbox

©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

4


Now,
review

the button click event handler in the code behind the page.
Notice that the
time is
formatted as a string.

Code Snippet:

protected

void

btnUpdateTime_Click(
object

sender,
EventArgs

e)

{


lblCurrentTime.Text =
DateTime
.Now.ToLongTimeString();

}


Preview

the page in the browser.

Click the button several times.
The time will update.
Did you see a
flicker?

You may have, or you may not have. Remember different
browsers and Internet connections can make the difference. Remember
that you are previewing the page using a local web server. So you are
not going through an Internet connection. Therefore the flicker
may not
be pronounced or visible as it would on a live web server.

AJAX can help stop the flickering in the web page when the page
content refreshed.

With

each click on the button,
the browser
will send the entire page
request, and
view state

back to the

server. Remember the
view state

has information about the state of all of the controls and elements on
the page.

Figure 2

is an image of how the page appears in the browser. The time i
s
displayed as well as an animated image of a clock and the button
labeled Display Current Time.

Managing Communication with AJAX

D
o
you really want a round trip every time someone clicks on a button
?

By default the entire request is
sent
to the server and
the response is returned,
each time
a request is made
.
AJAX

will help manage the
content as
it is

sent to the server and back.

How

does AJAX
manage the content and requests?

The

programmer will
define the areas
within the web page that n
eed
to
be
update
d and
therefore a request is sent

back on the server.

This area is known as the UpdatePanel.

So, if
the
user

click
s

on the button, the web page se
nds a call back to the server, and n
ot a
full
-
page

postback. On the server, the page life cyc
le will run as it did before. The HTML is rendered as it
was before and sent back complete to the browser.

Figure
2

WebForm1.aspx in the Web
Browser

©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

5


If
the
complete

code is sent to the browser
, why bother

with AJAX
?


The

browser will receive the full html

code
, but only update the content in the
area you defined.
Nothing else in the page is updated.

So,
only
part of the page is updated, and this
why the process
is called a partial update!

Cool!

What if the user disables JavaScript or does

no
t fully support the requirements for Ajax to work?

The

great thing about this is that the browser wil
l receive the entire HTML page. S
o
if the user
has disabled JavaScript, the browser will

just displays the
full
-
page

postback that it received.

What if the user clicks on the button so fast that the browser h
as not received the partial postback yet?

The partial postback is
asynchronous
, which means one way.
The browser will

send the request
one way and when
the web server receives a new response,

the old
requests

are ignored. So
only the most recent request
received by the web server
is received and processed.

Creating an Update Panel

WebForm2
.aspx

So, let’
s look at
an
example

that uses AJAX technology
. This is a modified version of the one that is in the
previous example
. Notice, the only thing

different i
s the addition of
control
s
,
ScriptManager
,
UpdatePanel

and
ContentTemplate
.
You can drag and drop the UpdatePanel on the page in design view
or type it in markup view.

You cannot in
clude FileInput control or
HtmlI
nputFile

control within an
UpdatePanel, bu
t they can be on the web page that contains an UpdatePanel.

The ContentTemplate is the area you will update. You can have mu
ltiple content areas defined. So
,
updating of one area can occur independent of the other areas on the page.

You must put a
ScriptM
anager

control on the page to manage the communication.
Because you may
want to use AJAX to update m
ultiple areas within a web page, the ScriptManager should be placed near
the top of the page code or at the top of the Content control.

Code Snippet:







<
asp
:
ScriptManager

ID
="ScriptManager1"

runat
="server"></
asp
:
ScriptManager
>


Note that when you save a web page that uses Ajax, you will see some JavaScript files may be saved as
well, such as ScriptResource.xsd and
Webresource.xsd

that

contain scripts needed to manage the page
interactions.



©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

6


Then,
in the markup view of the web form file,
notice how

the U
pdate
Panel in

the markup code

is
placed around the time label controls. The animated clock is not part of the UpdatePanel.


Code Snippet:



<
div
><
img

src
="Images/clock.gif"

/></
div
>



<
br

/><
br

/>



<
asp
:
UpdatePanel

ID
="UpdatePanel1"

runat
="server">


<
ContentTemplate
>



<
div
>



<
asp
:
Label

ID
="lblCurrentTime"

runat
="server"





Font
-
Bold
="True"></
asp
:
Label
>


<
br

/><
br

/>


<
asp
:
Button

ID
="btnUpdateTime"

runat
="server"





Text
="Display Current Time"



onclick
="btnUpdateTime_Click"

/>


</
div
>



<
br

/><
br

/>


<
asp
:
Label

ID
="lblError"

runat
="server"></
asp
:
Label
>



</
ContentTemplate
>


</
asp
:
UpdatePanel
>


The code file contains the same
button click event handler
as was in the first example.

Preview
view the
page

in a web browser
.
You should be able to update the time without seeing a flicker in the rest of the
page.

Sleep Delays


WebForm3
.aspx

Sometimes you need to be able to display content, but you don’t want it updated right away.
Sometimes you might want an interval of time to elapse before you update the content. AJAX provides
the ability to up monitor the progress of the request.
You can d
elay when the request is updated.

In
WebForm3.aspx, the markup

view

has the
same script manager, update panel,

content template and
controls as WebForm2.

The code view contains a script to run when the user clicks on the button. The Sleep

method is built
-
in
and

will cause the server to
temporarily delay

actions for
4

secon
ds. This delay occur
s on the server, not
the client. After
4

seconds on the server, then,

code moves to
the control to display the new time, with
seconds showing.

Code
Snippet:

protected

void

cmdRefreshTime_Click(
object

sender,
EventArgs

e)


{


System.Threading.
Thread
.Sleep(
TimeSpan
.FromSeconds(4
));


lblTime.Text =
DateTime
.Now.ToLongTimeString();


}

©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

7


UpdateProgress and ProgressTemplate


WebForm4.aspx

In WebForm4.aspx, the markup view has the same script manager, update panel, content template and
controls as WebForm3 and the same code in the code file.

The markup also includes a new element to monitor the progress. The
UpdateProgress

control
is used
to indicate the current state of the communication.
ProgressTemplate

is what to display during this
time. Now, the display is an animated GIF,
clock
.gif. That is why this is a simulation. You could run a loop
and draw out the image dynamically as t
he progress occurs, but that is beyond our point of this exercise.

In the code snippet below, the clock image is displayed in the Progress Template. So, the clock image is
only displayed while the code is waiting to be updated by the web server.
If you ha
ve more than one
UpdatePanel you can identify which UpdatePanel to use with the Progress with
AssociatedUpdatePanelID

set to the UpdatePanel ID.

Code Snippet:



<
asp
:
UpdateProgress

runat
="server"

id
="UpdateProgress1">


<
ProgressTemplate
>


<
div
><
img

src
="Images/clock.gif"

/></
div
>



</
ProgressTemplate
>


</
asp
:
UpdateProgress
>




When you prev
iew the page in the brow
ser

you can easily see the initial state

with no values displayed.
C
lick the button the

image and the progress template
shows

the image
. When the 10 seconds is up, the
image

is removed, because the
server has returned the response

to the browser. So the browser stops
displaying the Progress Template.

If you re
-
click the button before the time appears,
the call will be canceled and
the Progre
ss
Template
will start from the beginning

with a new request
.



©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

8


Intercept and Cancel AutoPostback Request

WebForm5.aspx

Let’s look at how we can use a
script to intercept th
is event, and then cancel the postback request. This
example contains the
similar

markup and code as in WebForm4, with a few additions.
Below is the code
for creating the UpdatePanel.

Code Snippet:

<
asp
:
UpdatePanel

UpdateMode
="Conditional"

ID
="UpdatePanel
1"

runat
="server">


<
ContentTemplate
>



<
div
>



<
asp
:
Label

ID
="lblCurrentTime"

runat
="server"





Font
-
Bold
="True"></
asp
:
Label
>


<
br

/><
br

/>


<
asp
:
Button

ID
="btnUpdateTime"

runat
="server"





Text
="Display Current Time"




onclick
="btnUpdateTime_Click"

/>


</
div
>



<
br

/><
br

/>


<
asp
:
Label

ID
="lblError"

runat
="server"></
asp
:
Label
>



</
ContentTemplate
>

</
asp
:
UpdatePanel
>


Below is the code that is called when the click event occurs on the button. The time is not updated until
after 4 seconds.

Code Snippet:




System.Threading.
Thread
.Sleep(4000);


lblCurrentTime.Text =
DateTime
.Now.ToLongTimeString();


The following code is added to the markup view that will appear within the ProgressTemplate when a
request is made to update the page. If the user clicks on the Cancel button, the
AbortPostBack

function
is called which will cause the asynchronous postback
to be cancelled.

Code Snippet:


<
asp
:
UpdateProgress

runat
="server"

id
="UpdateProgress1">


<
ProgressTemplate
>


<
div

id
="lblMessage"

/><
br

/>


<
input

type
="button"

value
="Cancel"

onclick
="AbortPostBack()"

/>



</
ProgressTemplate
>


</
asp
:
UpdateProgress
>



Remember that t
he browser

is managing the requests. In the browser
the life cycle for asynchronous
postbacks

are managed by t
he
Sys.WebForms.PageRequestManager

clas
s located within the Microsoft
AJAX Library
.
A
synchronous postbacks
can be customized and managed
by handling events exposed by
the
PageRequestManager

class.

T
he
initializeRequest

event of the PageRequestManager class
is the
object used to

cancel the currently executing asynchronous postback.

©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

9


Becaus
e you need to intercept the request, you can use simple JavaScript to cancel the request. Because
these web pages use master and content pages, the JavaScript has to be placed within the first Content
control.

Below is the JavaScript that creates the Page
RequestManager objects

(PRM)
.
PRM represents the
PageRequestManager object.
This is a client
-
side JavaScript, so that it does not need to be included in
the form element. The code could also be placed on the bottom of the page only to help keep it
separate
d from the other code.

Note that you won’t be asked to explain this code. But you should know that you are intercepting the
event and changing it to cancel it in the browser.

The
set_cancel

will cancel the asynchronous postback
request.

Code Snippet:



<
script

type
="text/javascript">

var

prm = Sys.WebForms.PageRequestManager.getInstance();


prm.add_initializeRequest(CheckStatus);



function

CheckStatus(sender, args) {


if

(prm.get_isInAsyncPostBack())


{


args.set_cancel(
true
);


}


}


function

AbortPostBack() {


if

(prm.get_isInAsyncPostBack()) {


prm.abortPostBack();


}


}




</
script
>

When you preview the page you will see that you can quickly cancel the request and the time is not
updated.

Triggers

WebForm6
.aspx

Some web forms cause a postback to occur when certain events occur such as a change in the selected
value of a dropdown lis
t or when the user clicks a button. Using AJAX, the web application can contain
controls that are configured to initiate the postback request independently. This allows the control to
request an update, for example, when a value changes.

In this example,
there are

several form fields that
cause a property
on a control or the page,
to be
modified
.
These examples are often demonstrated in books as a card maker, but you can use this
method for many reasons such as to update the web site based on a user’s pref
erence. You can also use
©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

10


the information gathered to generate content such as an advertisement on the page. The data can come
from the user, but it can also be retrieved from other sources such as a cookie or database.

Open the WebForm6.aspx file and prev
iew the code in markup view.
The
ScriptManager

is placed at the
top of the markup view. Look at the ContentTemplate in the UpdatePanel. None of the form fields on
the left are in the UpdatePanel, just the label and image

inside the panel control

on the right.
You do not
need to use a panel control with the UpdatePanel. However, the panel control is used to help with
layout of the content in the page. Some authors use absolute positioning with panel controls and other
controls using the style tag.

However, as shown in this example, you can accomplish the same task using
the style tag and margin properties.

Figure 3 below displays o
n the left panel, a form which provides the ability to enter text, select images,
select options from dropdownlists a
nd radiobutton lists, and selecting a date from a panel control.
When the form is processed, the values will be used in the right panel.


Figure
3

WebForm6 Processing a Form



©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

11


In the code
in

the markup view,
are form field contro
ls used to create

the form in the first panel.
These
form field controls include textboxes with the
TextMode

set to single and multiple lines, image buttons,
dropdownlists, radiobuttonlists, and a calendar control.

Preview the page in the browser. You can click on the image buttons and that will send a signal to
process the form. You can click on the calendar date and the form will be reprocessed. You can click on
the submit button and the form is reprocessed. Each t
ime the form is resubmitted, the right panel is
completely replaced with the new code.

In the code
file

you find the code
,

which created the second panel that shows the results selected by the
form.
The code also
creates ArrayLists

used to store the value
s from the Color enumeration, installed
fonts, font size and border styles.
A calendar control is used to allow the user to select a date, which is
assigned to a label control.

The form processing
retrieves the values from the form fields and uses the val
ues or shows the results
selected in the form. Values and properties returned can be used or displayed within the second panel.
Notice that some values such as the font size and border styles cannot simply be used to set the
property for the control. The v
alues must be converted into the appropriate object type.

Preview the page in the browser. Notice that you can update sections of the page, by clicking on the
submit button, or the car images. The car images are buttons and their click event handler will
also
update the second panel. But notice how the entire page has to be refreshed when this event occurs.

Triggers

WebForm7.aspx

This page contains the same markup and code as in the previous example. However, we will modify this
page so that when you mak
e different selections, the content will update in the second panel, without
causing the entire page to refresh and flicker. To accomplish this task, the web page will make use of
triggers.
Triggers

are similar to triggers in database processing. When an e
vent occurs, that can trigger,
or start, a process. The process in this case is to update the data in the second panel with the form
values.

This code is basic ASP and you can view it in the editor.

The first step is to configure the controls to
initiate

a postback by creating a set of triggers. These
triggers are called
AsynchPostBackTrigger
. That means that the control

can call the
autosync
h
ronous

postback to the web server. The control id needs to be passed to identify the source of the trigger.

At the top of the page in markup view, insert the code to create the script manager.


Code Snippet:


<
asp
:
ScriptManager

ID
="ScriptManager1"

runat
="server"></
asp
:
ScriptManager
>





©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

12


T
he
UpdatePanel and ContentTemplate c
ontrol
s were inserted around the right panel control.


Code Snippet:


<
asp
:
UpdatePanel

ID
="UpdatePanel1"

runat
="server">

<
ContentTemplate
>


<
asp
:
Panel

ID
="RightPanel"

runat
="server"

HorizontalAlign
="Center"



BorderStyle
="Outset"

BorderColor
="#660066"

BackColor
="#FFE2C6"

>

. . .


</
asp
:
Panel
>

</
ContentTemplate
>

</
asp
:
UpdatePanel
>


Triggers are inserted
within

the UpdatePanel control.

The code is placed immediately above the closing
UpdatePanel tag as you can see in the snippet.


Code Snippet:




. . .


</
ContentTemplate
>


<
Triggers
>


<
asp
:
AsyncPostBackTrigger

ControlID
="txtAdName"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="txtAdLocation"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="txtAdDescription"

/>



<
asp
:
AsyncPostBackTrigger

ControlID
="imgGreenCar"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="imgLightBlueCar"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="imgPinkCar"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="imgRedCarPresent"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="imgRedWhiteCar"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="imgYellowConvertable"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="DDLBackColors"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="DDLFontColors"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="DDLFontFamily"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="DDLFontSize"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="RBLBorderStyle"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="Calendar1"

/>


<
asp
:
AsyncPostBackTrigger

ControlID
="btnSubmit"

/>



</
Triggers
>


</
asp
:
UpdatePanel
>



To help the programmer,
Visual Studio .NET provide
s a graphical inter
face to select triggers from a list,
rather than typing them in. However, the programmer has to be in design view first and c
lick on the
UpdatePane
l, which isn’t easy to locate. T
here are no visual
cues to where the UpdatePanel is located.
There are two
way
s to select the UpdatePanel, First you can
select it from the control navigation tree at
the bottom of the window.
Or, you can select the UpdatePanel control

in the Properties Window
.



©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

13


As you can
see in Figure 4, the Triggers are listed as a Collection in the Properties window for the
UpdatePanel control. Click the build icon, which looks like three dots, and the
UpdatePanelTrigger

Collection Editor window opens. Click the Add dropdown list to sel
ect
AsyncPostBack
. Then you can
select the control using the
ControlID

dropdown list. Repeat the process for each control that needs to
have a trigger and then click the OK button.

Using this graphical user interface is optional. You can simply type in th
e code, which was shown earlier.
However, using graphical editors can help the programmer decrease data entry errors.


Figure
4

Creating a Collection of Triggers for the UpdatePanel

The control can be assigned to

an AsyncPostBack
, or a full PostBack trigger. The
PostBackTrigger

will
cause a full postback such as if you used a submit button to update the form.

Preview the page in the browser. Since each time only the thing

that is different is updated in the panel,
you can see that

the page updates without flickering.

Note that
when

you save
a

web page that uses Ajax, you will see some JavaScript files saved as well,
such as ScriptResource.xsd and Webresource.xsd
that

contain scripts needed to manage the page
interactions.



©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

14


Time

WebForm8
.aspx

So, you have already seen how to run
a

clock on the server and execute code within a specific time
frame. But, what if you want the page to refresh automatically?

In the past, you would use the meta tag
and refresh the page on the client side.

Th
ere is
a catch with using the server side timers. It isn’t a good thing to

overwork

the server. It is more
efficient to r
efresh only that which you need
and only
when you n
eed it.
The solution is to

add a Timer
control and set the interval to the number of milliseconds.

There are

60,000

milliseconds in

one minute.
The timer will raise a server side Tick event
at that time,
which you can int
eract with through the
program code
.

Open the WebForm8 in markup view.
In this example the refresh will occur every 10 seconds
automatically. The script manager is included at the top of the page.
In markup view add the
UpdatePanel and ContentTemplate.

The UpdateMode

is set to Conditional

to only allow the partial
updating.

In markup view the
Timer is defined outside of the UpdatePanel. And, see that when the
OnTick

event
handler is intercepted, the TImerControl1_Tick is called.
When the TimerControl1_Tick method is called,
the code runs.


In the markup view, there is an AsyncPostBackTrigger defined for the Timer control to be executed
when the Tick event occurs. The
EventName

identifies the event in the trigger. That is the Event that will
be called when the postback occurs.


Code Snip
pet:

<
asp
:
ScriptManager

ID
="ScriptManager1"

runat
="server"



EnablePartialRendering
="True"

/>





<
div
><
img

src
="Images/clock.gif"

/></
div
>



<
br

/><
br

/>



<
asp
:
UpdatePanel

ID
="UpdatePanel1"

runat
="server"

UpdateMode
="Conditional">


<
ContentTemplate
>



<
div
>



<
asp
:
Label

ID
="lblCurrentTime"

runat
="server"

Font
-
Bold
="True"

/>


<
br

/><
br

/>


<
asp
:
Button

ID
="btnUpdateTime"

runat
="server"

Text
="Refresh Time"




style
="
height
: 26px"

/>


</
div
>



</
ContentTemplate
>


<
Triggers
>



<
asp
:
AsyncPostBackTrigger

ControlID
="TimerControl1"

EventName
="Tick"

/>


</
Triggers
>


</
asp
:
UpdatePanel
>


<
asp
:
Timer

ID
="TimerControl1"

runat
="server"



Interval
="1000"

OnTick
="TimerControl1_Tick"

/>





©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

15


In the code file you can see that
only
if the
full
-
page

load

occurs, the time is updates in the label control.

Code Snippet:



protected

void

Page_Load(
object

sender,
EventArgs

e)


{


lblCurrentTime.Text =
DateTime
.Now.ToLongTimeString();


}


protected

void

TimerControl1_Tick(
object

sender,
EventArgs

e)


{


int

tickCount = 0;


if

(ViewState[
"TickCount"
] !=
null
)


{


tickCount = (
int
)ViewState[
"TickCount"
];


}


tickCount++;


ViewState[
"TickCount"
] = tickCount;


if

(tickCount > 10)


{


TimerControl1.Enabled =
false
;


}


}

AJAX Control

ToolKit



Your book includes a section on the
AJAX
Control
Toolkit
, a free set of tools, used to fur
ther develop
Ajax applications.


If you want to view one of them, right click
the control

and view it in the browser.
You’ll see some really fantastic effects.
There are over 40 controls free with the toolkit.

It is important to understand the difference between the AJAX control and a control extender. An
Extender will add features to an exis
ting ASP.NET control. For example you may have a textbox but now
you can have
autocompletion
, allowing the user to enter a partial word and a list of possible matches
will appear in a dropdown list. A
CalendarExtender

allows the calendar control to attach
to a textbox to
that the date is easily selected and automatically entered into the textbox.
CascadingDropDown

is an
extender that links dropdown list controls to make dynamically populating lists easier.

The process for installing the toolkit will be dif
ferent on each system. If you are interested in working
with these new controls, you will need to install the toolkit from the
CodePlex

web site and then setup
the web project to use the controls. You may need to register the controls within the individual

web
pages, or within the web configuration files.

As a student, you are not required to install the toolkit. However, from experience, many students find
these controls worth the additional effort. They truly enhance the user experience and the appearanc
e
of the web applications.



©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

16


Installing the AJAX Toolkit

The following steps are included for students who might be looking for some assistance with using these
tools.
This was installed on a Windows 7 system, with Visual Studio 2010 Professional installe
d. You
must have administrative rights on the computer that you are installing this program. Make sure Visual
Studio is closed and you are logged in as administrator.

This process requires a third party program called
NuGet

to help east the installation of the AJAX Toolkit.
This program is free, downloadable, and has been downloaded over 212,000 times already!

However, it
is also possible to install the AJAX Control Toolkit without NuGet, but you have to download the zip fi
le,
uncompress it and install the files manually. The benefit of NuGet is that you can install other third party
programs using the NuGet management tool.

NuGet requires you to already have Windows PowerShell 2.0 Tools installed. So, the first step is to
install
PowerShell 2.0 Tools

if you do not have PowerShell 2.0 Tools. You can download Power Tools from this
link,
http://support.microsoft.com/kb/968929
.

Then, you will install NuGet.
The version of
NuGet is 1.6.21205. The NuGet is a free open
-
source tool to
help you load third party libraries into your .NET applications. You can download NuGet at
http://visualstudiogallery.msdn.microsoft.com/27077b70
-
9dad
-
4c64
-
adcf
-
c7cf6bc9970c/file/37502/19/NuGet.Tools.vsix
.
Simply double
-
click on this file to launch the program.
You may need

to accept the license agreement. There are no settings to configure.

After installing NuGet, you can follow the directions to install the AJAX Toolkit located on this web page,
http://www.asp.net/web
-
forms/tutorials/ajax
-
control
-
toolkit/getting
-
started/get
-
started
-
with
-
the
-
ajax
-
control
-
toolkit
-
cs
.

After the program is installed,
launch Visual Studio and open your web forms applications project.
Right
click on your project folder in the solution explorer panel. Select Manage NuGet Packages.
Click the
online menu item in the left panel. In the Search text box type AJAX Control Toolk
it and press enter.
Locate and click on the toolkit in the center pane then click the Install button that appeared.

After the installation is complete you can click the Close button to close the program. Note that in the
project folder inside of the Solut
ion Explorer window, you will see an object called References. If you
click on it you will see the list of references to the namespaces and third party libraries available within
your application. Notice that you now will have an entry for the
AJAXControlT
oolkit
.

To add the controls in the Toolbox, right click on the Toolbox and select Add Tab. Name the tab
AJAX
Control Toolkit. Right click in the area for the controls for that tab, and select Choose Items. Locate the
AjaxControlToolkit.dll file. For this
week’s project, they are located in the
AJAX
\
packages
\
Aja
xControlToolkit.4.1.51116
\
lib
\
[ver] where [ver] represents either 35 or 40, the
versions of ASP you are using for your project. The controls will all be selected and added. Click the
button to close
the window. You will see all the controls now populate the tab!

©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

17


Working with AJAX Controls

Once the package is installed into your web project, you will
register the code in the web configuration
file or in the page where you want to use the controls
.

Belo
w is the code to register the toolkit in the
web pages.

You can also drag and drop controls onto your page and they can be auto
-
registered by
Visual Studio.

Code Snippet:


<%
@

Register

TagPrefix
="asp"

Namespace
="AjaxControlToolkit"

Assembly
="AjaxControlToolkit"
%>



Twitter

Feed



WebForm9.aspx

Twitter

is a real popular social media technology now. So this example will add the Twitter to the web
page.
Similar to texting, twitter lets you post 140 character messages. Remember that these are pu
blic
messages. Once it is out there, you can’t take it back!

First, you need to drag and drop a ScriptManager control from the AJAX Extensions tab in the Toolbox to
the page. Remember that all of your AJAX enabled pages need this control to be included on
the page.

Y
ou can simply drag and drop the Twitter control from the AJAX Control Toolkit tab in the Toolbox onto
the page.

The main properties that apply to the Twitter control are
IncludeReplied
,
I
ncludeRetweets
,
ProfileImageUrl
,
ScreenName

and
Mode

that

can have values of Profile and Search.

You can set these in
markup view or code view.

For this sample page the
ScreenName

is set to
ScottGu, which is Scott Guthrie, father of ASP. His Twitter
page is
https://twitter.com/#!/scottgu
. So, in the Properties window,
the
ScreenName

was changed t
o
ScottGu.

The
Caption

was changed to
Scott Gu's Tweets
. The Title and ToolTip were changed to
Follow
Scott on Twitter
. The
Count
, which is the number of tweets di
splayed,

was changed from the default 5
to 10. By default a class will be applied to the control named
ajax__twitter
. But you can change this at
any time in the Properties window.
The
W
idth

was changed to 300. The
ProfileImage

was changed to
Images/Bird.pn
g.

Preview the code in the browser and see how the twitter feed looks!

Below is the code snippet
containing the AJAX Twitter control,
which was used to create the
twitter feed
on the ASP page.



©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

18


Code Snippet:


<
asp
:
ScriptManager

ID
="ScriptManager1"

runat
="server"></
asp
:
ScriptManager
>



<
ajaxToolkit
:
Twitter

ID
="Twitter1"

runat
="server"

Caption
="Scott Gu's Tweets"



Count
="10"

CssClass
="ajax__twitter_footer"

ScreenName
="ScottGu"



Title
="Follow Scott on Twitter"

ToolTip
="Follow Scott on T
witter"



ProfileImageUrl
="images/bird.png"

Width
="300px">


<
EmptyDataTemplate
>


There are no matching tweets.


</
EmptyDataTemplate
>


<
LayoutTemplate
>


<
div

runat
="server"

class
="ajax__twitter_header">


<
asp
:
Image

runat
="server"

ImageUrl
="images/bird.png"

/>


<
h3

runat
="server">
Follow Scott on Twitter
</
h3
>


<
h4

runat
="server">
Scott Gu
&#39;
s Tweets
</
h4
>


</
div
>


<
ul

runat
="server"

class
="ajax__twitter_itemlist"




style
="
margin
:0px;">


<
asp
:
PlaceHolder

runat
="server"

ID
="ItemPlaceholder"

/>


</
ul
>


<
div

runat
="server"

class
="ajax__twitter_footer">


<
asp
:
Image

runat
="server"

ImageUrl
="images/bird.png"

/>


</
div
>


</
LayoutTemplate
>

</
ajaxToolkit
:
Twitter
>





©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

19


HTMLEditorExtender


WebForm10
.aspx

Now we will look at one example of using an AJAX control. In web sites, we collect data from users
through forms. These are usually blank text forms that only allow basic text characters.
This is an
example of an
AJAX Control Extender
, which extends the capab
ilities of other controls beyond

the
original control.

But what if the user wants to format the text so it is more readable, using headings, styles and
formatting? They cannot do this
with the current basic textbox controls. However, in the early days of
ASP, third party companies such as
FreeTextBox

and
Telerik

built textbox controls. Today, many
companies continue to use third party controls to provide a robust text
-
editing environmen
t for their
web applications. However, with the AJAX Toolkit, we can build a web form that allows the user to enter
content and format the content using formatting and style tools, without the need for a third party tool.

In this example, you will learn t
o implement the
HTMLEditorExtender

control. This control provides
more stability over the earlier versions and is compliant with HTML 5 standards.

Open
WebForm10

in markup view.
First make sure that the
AJAX Control Toolkit is registered in the web
page. You’ll have to do this manually for the extenders. Notice the
TagPrefix

is asp.

Code Snippet:


<%
@

Register

Assembly
="AjaxControlToolkit"

Namespace
="AjaxControlToolkit"

TagPrefix
="asp"

%>




Next the markup code should have the page content and the
TextBox

control. There is a basic ASP
TextBox with mode set to
MultiLine

and the ID is TextBox1.

Code Snippet:

<
asp
:
TextBox

ID
="TextBox1"

runat
="server"



TextMode
="MultiLine"

Columns
="60"

Rows
="8"

/>




Next you would normally make sure that the ScriptManager tag has been inserted into the page. But in
this case you will insert a special Toolkit Script Manager.

Code Snippet:



<
asp
:
ToolkitScriptManager

ID
="ToolkitScriptManager1"

runat
="server">


</
asp
:
ToolkitScriptManager
>





©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

20


To insert the extender, click

on the textbox control and in the smart icon, and
click on

Add Extender.
Select
HtmlEditorExtender

and the default ID will be
TextBox1_HtmlEditorExtender
. Click OK.

Notice the
TargetControlI
d

is used to locate the

ID of textbox to extend with
HtmlEditor

controls.

The
Toolbar

provides the ability to customize toolbar and the buttons on the toolbar. If no toolbar with at
least one button exists then the default toolbar
with all the buttons would be used.

In the Properties window, a property for the TextBox1 control is added called TextBox1
_
HtmlEditorExtender
. You will see specific attributes such as the
ScriptPath
,
SanitizerProvider

and
Toolbar. The Toolbar is a collec
tion of toolbars and buttons.
If you click on the Collections icon in the
Properties window, for the extender property, you

can insert the various buttons. The code snippet
following shows the buttons available within a toolbar.


Code Snippet:

<
asp
:
HtmlEditorExtender

ID
="TextBox1_HtmlEditorExtender"

runat
="server"


Enabled
="True"

TargetControlID
="TextBox1">


<
Toolbar
>



<
ajaxToolkit
:
Undo

/>


<
ajaxToolkit
:
Redo

/>


<
ajaxToolkit
:
Bold

/>


<
ajaxToolkit
:
Italic

/>


<
ajaxToolkit
:
Underline

/>


<
ajaxToolkit
:
StrikeThrough

/>


<
ajaxToolkit
:
Subscript

/>


<
ajaxToolkit
:
Superscript

/>


<
ajaxToolkit
:
JustifyLeft

/>


<
ajaxToolkit
:
JustifyCenter

/>


<
ajaxToolkit
:
JustifyRight

/>


<
aja
xToolkit
:
JustifyFull

/>


<
ajaxToolkit
:
InsertOrderedList

/>


<
ajaxToolkit
:
InsertUnorderedList

/>


<
ajaxToolkit
:
CreateLink

/>


<
ajaxToolkit
:
UnLink

/>


<
ajaxToolkit
:
RemoveFormat

/>


<
ajaxToolkit
:
SelectAll

/>


<
ajaxToolkit
:
UnSelect

/>


<
ajaxToolkit
:
Delete

/>


<
ajaxToolkit
:
Cut

/>


<
ajaxToolkit
:
Copy

/>


<
ajaxToolkit
:
Paste

/>


<
ajaxToolkit
:
BackgroundColorSelector

/>


<
ajaxToolkit
:
ForeColorSelector

/>


<
ajaxToolkit
:
FontNameSelector

/>


<
ajaxToolkit
:
FontSizeSelector

/>


<
ajaxToolkit
:
Indent

/>


<
ajaxToolkit
:
Outdent

/>


<
ajaxToolkit
:
InsertHorizontalRule

/>


<
ajaxToolkit
:
HorizontalSeparator

/>


</
Toolbar
>

</
asp
:
HtmlEditorExtender
>



©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

21


Preview the page in the browser. Click inside the HTML text box and enter some text. Try some of the
buttons out to see how they compare to using a word processor.


Figure
5

H
TML Extended Editor from the AJAX Control Toolkit

You can simply assign the values of the textbox to another control or store it somewhere.
The control
sends out the HTML with the content.

Code Snippet:




Label1.Text =
"Here is what you entered.<br /><br />"



+ TextBox1.Text;


TextBox1.Text =
""
;


Preventing Cross
-
Site Scripting Attacks with
AntiXss

One of the problems you can have with input controls, is that they can be a source for hackers to enter
in content, which can help them breach your networks, applications and
systems. Validation tools are
helpful. However, when working with the AJAX controls, you can use a tool called the
Sanitizer Provider

to help prevent these
Cross
-
Site Scripting (XSS) Attacks
. There are many articles on the web on XSS
attacks, and they are
very common today. Sometimes they inject a simple JavaScript into each web
page, but that JavaScript can be very dangerous. Preventing XSS attacks is an important requirement for
a web developer.

The
basic AJAX HTML Editor will use the
SanitizerProvider

that will return the Sanitizer Provider

or null
(meaning nothing),
when no S
anitizer Provider is configured in the web page.
You

need to use the

AntiXss Sanitizer Provider

then your website will be open to Cros
s
-
Site Scripting (XSS) Attacks.
Specifically
the

AntiXSS Sanitizer Provider is included in the SanitizerProviders

folder with

the

Ajax
Control Toolkit found at the CodePlex.com web site. The folder contains three assemblies,
SanitizerProviders.dll, AntiXSSLibrary.dll, a
nd HtmlSanitizationLibrary.dll,

which need to be added in the
web configuration file.

©
2012
,
All Rights Reserved, Author: Katie Kalata,


Last Updated:
11/5/2013

This content may not be reproduced without permission.

Page

22


You can download
AntiXss
into your web application using the NuGet program you installed earlier.

If you downloaded NuGet you can install the Toolkit and AntiXss with each application. The NuGet also

allows you to download other kinds of tools such as
JSON

the JavaScript library of code often referred to
as
JQuery
.

You can register the Sanitizer in the web configuration file. Make sure to insert the
configSections

immediately below the configuration
no
de. It must be the first child node in that section.

Code Snippet:



<
configuration
>


<
configSections
>


<
sectionGroup

name
=
"
system.web
"
>


<
section

name
=
"
sanitizer
"

requirePermission
=
"
false
"




type
=
"
AjaxControlToolkit.Sanitizer.ProviderSanitizerSection,


AjaxControlToolkit
"
/>


</
sectionGroup
>


</
configSections
>


In older versions of ASP such as ASP 3.5 you might need to place this in the
system.web

node in the web
configuration file. Since our programs are written in version 4, this is not required.

Code Snippet:



<
system.web
>



<
sanitizer

defaultProvider
=
"
AntiXssSanitizerProvider
"
>


<
providers
>


<
add

name
=
"
AntiXssSanitizerProvider
"





type
=
"
AjaxControlToolkit.Sanitizer.





AntiXssSanitizerProvider
"
></
add
>


</
providers
>


</
sanitizer
>