Vous êtes sur la page 1sur 100

RadAjax for ASP.

NET AJAX

RadAjax for ASP.NET AJAX


RadAjax for ASP.NET AJAX

Table of Contents
1. Introduction 1
1.1. What is AJAX? 1-2
2. Advantages 3
2.1. No Modifications to Your Application 3-6
2.2. Intuitive Way for Defining AJAX Relations 6-8
2.3. Codeless Development 8-10
2.4. Centralized Management of AJAX Relations 10-12
3. Getting Started 14
3.1. How RadAjax Works: Controls And Configuration 14-15
3.2. Design Time of RadAjax Controls 15-18
3.3. Getting started: AJAX-enable a scenario through RadAjaxManager and 18-21
LoadingPanel
3.4. Server-Side OverView 21
4. Changes and backward compatibility 22
4.1. RadAjax for ASP.NET vs RadAjax for ASP.NET AJAX 22-23
4.2. What's New in RadAjax for ASP.NET AJAX 23-24
4.3. Changes and backwards compatibility 24-27
4.4. Current RadAjax Limitations 27-28
4.5. Back and Forward browser buttons (browser history) 28
5. RadAjaxManager Control 29
5.1. AJAX Manager 29-31
5.2. How-To 31
5.2.1. Add AjaxSettings programmatically 31-32
5.2.2. RadAjax and WebUserControls 32-34
5.2.3. RadAjax and MasterPage 34-35
5.2.4. MasterPages: ajaxify and update controls in master and content 35-37
page
5.2.5. MasterPages: initiating requests from one ContentPlaceHolder and 37-38
loading/updating controls in another
5.2.6. Ajaxify particular templated GridView buttons 38-40
5.2.7. Update in composite control 40-41
5.3. Troubleshooting 41
RadAjax for ASP.NET AJAX

5.3.1. Ajaxifying controls wrapped in RadAjaxPanel and added to AJAX 41-43


Manager settings
5.3.2. Ajaxified control still postbacks 43
5.3.3. AJAX Manager Designer does not locate all controls 43-44
5.3.4. Layout problem: Updated controls on new line 44-45
5.3.5. SharePoint WebPart: Dynamically added manager is missing in 45
Page.Controls
6. RadAjaxPanel Control 46
6.1. AJAX Panel 46-48
6.2. How-To 48
6.2.1. Achieve interaction between AJAX Panels 48-49
6.2.2. Scroll to top after AJAX 49-50
7. AJAX Manager Proxy 51
7.1. AJAX Manager Proxy 51-52
8. RadAjaxLoadingPanel Control 53
8.1. AJAX Loading Panel 53-54
8.2. How-To 54
8.2.1. Show and hide loading panel explicitly 54-55
8.2.2. Show RadAjaxLoadingPanel on initial page load 55-56
8.2.3. Show the loading panel next to AJAX initiator 56-57
8.2.4. Center LoadingPanel on the Screen 57-58
9. Client-Side 59
9.1. Client-Side API 59-61
9.2. Client side Events 61
9.3. RadAjaxManager Client Object 61-62
9.4. RadAjaxPanel Client Object 62-63
9.5. OnRequestStart 63-64
9.6. OnResponseEnd 64
9.7. Client-side How-To 64
9.7.1. Executing custom javascript code after AJAX update 64-65
9.7.2. Cancel AJAX request 65
9.7.3. Client confirmation and AJAX 65-66
RadAjax for ASP.NET AJAX

9.7.4. Pass more than one argument 66


9.7.5. Forcing postback 66-67
9.7.6. Assign different Client-events for different controls 67
9.7.7. Change mouse cursor on AJAX update 67-68
10. General FAQ and How-to 69
10.1. Frequently Asked Questions 69
10.2. Redirecting to another page 69-70
10.3. Load user controls 70-72
10.4. Manually add an AJAX request to a client-side event of an HTML 72-73
element
10.5. Exclude controls from ajaxifying 73-75
10.6. Incompatible controls and updating 3rd party controls with Telerik 75-76
RadAjax
10.7. Disable AJAX when client browser does not support it 76
10.8. Disable controls during AJAX 76-77
10.9. How to use Css Conditional Comments with Ajax 77-78
10.10. Download files with ajaxified control 78
10.11. Ajax requests queueing 78
11. General Troubleshooting 79
11.1. Known reasons for error messages 79
11.2. Most Common Mistakes 79-80
11.3. AJAX And File Upload 80
11.4. Control is not updated after AJAX 80-82
11.5. Dropped Ajax requests from child window 82
11.6. Ajax, ViewState, and Firefox 82-83
11.7. Controls Not Compatible with RadAjax for ASP.NET AJAX 83-84
11.8. Error Handling For Ajax Requests 84
12. Performance 85
12.1. Optimizing client-side performance 85
13. RadAjax Appearance and Styling 86
13.1. Controlling Appearance 86
14. RadAjax Server-Side Programming 87
14.1. RadAjaxControl Properties 87-88
RadAjax for ASP.NET AJAX

14.2. OnAjaxRequest event 88-89


14.3. OnAjaxSettingCreating event 89-90
14.4. OnAjaxSettingCreated event 90
14.5. RadAjaxControl Methods 90-92
14.6. Server Side Events 92
15. RadCodeBlock and RadScriptBlock 93
RadAjax for ASP.NET AJAX 1

1  Introduction
1.1  What is AJAX?
The core idea behind AJAX is to make the communication with the server asynchronous, so that data is
transferred and processed in the background. As a result the user can continue working on the other parts of
the page without interruption. In an AJAX-enabled application only the relevant page elements are updated
and only when necessary.

In contrast, the traditional synchronous (postback-based) communication requires a full page reload each time
data is transferred to/from the server. This leads to the following negative effects:
 Poor Interactivity - the user interaction with the application is interrupted by a postback every time a
server call is needed.
 Ineffectiveness - the full page is rendered and transferred to the client on each postback. This
process is time consuming and traffic intensive.
 Low Usability - the requirement for full page postback whenever the user interface is changed imposes
hefty limitations on the degree of sophistication a web user interface can achieve. Before AJAX, rich and
smooth interfaces with on-demand updates could only be implemented using Flash technology.

AJAX-enabled applications, on the other hand, rely on a new asynchronous method of client-
server communication. It is implemented as a JavaScript engine that is loaded on the client during the initial
page load. From there on, this engine serves as a mediator that sends only relevant XML-formatted data to the
server and subsequently processes the server response to update the relevant page elements.
Below is a diagram of the complete lifecycle of an AJAX-enabled web form.

1. Initial request by the browser – the user requests a particular URL.


2. The complete page is rendered by the server (along with the JavaScript AJAX engine) and sent to the
client (HTML, CSS, JavaScript AJAX engine).
3. All subsequent requests to the server are initiated as function calls to the JavaScript engine.
4. The JavaScript engine then makes an XmlHttpRequest to the server.
5. The server processes the request and sends a response in XML format to the client (XML document). It
contains the data only of the page elements that need to be changed. In most cases this data comprises
just a fraction of the total page markup.
6. The AJAX engine processes the server response, updates the relevant page content or performs another
operation with the new data received from the server. (HTML + CSS)

AJAX development however is a quite complex process. It requires:


 Intensive JavaScript coding - this may turn to be a problem for a large number of .Net developers.
RadAjax for ASP.NET AJAX 2

Furthermore, the lack of good debugging tools for client-side script makes the process even more
complicated.
 Comprehensive knowledge of the ASP.NET page lifecycle - AJAX applications typically break the normal
page life-cycle and do not work properly. As a result developers have to handle ViewState management,
EventValidation, and preservation of client-scripts.

The Telerik Telerik RadAjax framework (telerik-ajax.html) eliminates those challenges. The product
features Telerik's Click-and-Go™ patent -pending technology, which allow you to jump-start your AJAX
development today:
 AJAX-enable any existing or new application, regardless of its level of complexity
 You don't need detailed knowledge of AJAX.
 You don't have to modify your application - you do not need to place Update Panels, set triggers, manually
invoke AJAX requests, etc.
 You don't have to write a single line of code (JavaScript or server-side)

For more information see section: "Advantages of Telerik AJAX framework (Section 2.1)".
RadAjax for ASP.NET AJAX 3

2  Advantages
2.1  No Modifications to Your Application
The greatest advantage of the Telerik RadAjax tool is that you don't need to make any changes to your existing
applications or build new ones in some specific way so that they can be AJAX-enabled. RadAjax for ASP.NET
AJAX uses the Microsoft ASP.NET AJAX engine to ajax-ify applications, however eliminates the need of using
numerous UpdatePanels, triggers, etc.
The patent-pending Click-and-Go™ technology of Telerik RadAjax for ASP.NET AJAX allows you to AJAX-
enable any ASP.NET application without making any modification, without writing a single line of code:
 Existing applications - in order to AJAX-enable an existing application you need to simply add
Microsoft ASP.NET AJAX to your project, then drop the AJAX Manager (Section 5.1) control at the
bottom of your form, define the AJAX relations using a single dialog in Visual Studio and hit F5.
 New applications - you don't have to follow any specific guidelines when building an application that is
to be AJAX-enabled with Telerik RadAjax. Simply build a regular postback-based application the way you
are used to and use the AJAX Manager (Section 5.1) to AJAX-enable it at the end.

2.1.1 AJAX-enabling without RadAjax for ASP.NET AJAX


When using microsoft ASP.NET AJAX, the standard approach to AJAX-enable am application will require you
to place "UpdatePanels" around each area that needs to be updated. This may introduce some challenges with
preserving the application's layout (i.e. you need to figure out how to group the various elements).

In simple scenarios like the one above placing UpdatePanels may not be very difficult. But imagine you have a
real-life application (e.g. Telerik HelpDesk sample) with dozens of UI controls that need to start working with
AJAX. Placing 20+ UpdatePanels and figuring which element should go in the respective panel may be a
challenge even for the most advanced developers.
RadAjax for ASP.NET AJAX 4

2.1.2 AJAX-enabling a sample application with Telerik RadAjax for ASP.NET AJAX
Telerik RadAjax for ASP.NET AJAX offers a fundamentally different approach to AJAX-enabling existing
applications. Basically you need to perform two easy tasks:
1. Drag and drop the AJAX Manager control on your form
2. Set the AJAX relations using a single dialog in Visual Studio .Net design mode

As a result, the simple application discussed before will look as shown below - the only modification is the
AJAX Manager control placed at the bottom of the form. All controls above it remain intact in their original
state.
RadAjax for ASP.NET AJAX 5

Once the AJAX Manager is placed on the form you need to use its configuration dialog to define the AJAX
relations among the controls on the page, i.e. which controls should initiate AJAX request and which controls
should be updated by each respective AJAX request. In our example there are two such relations:
1. When the calendar control is clicked the e-mail list (datagrid) and the message body (div) need to be
respectively updated
2. When an e-mail message is clicked the message body needs to be updated

Those two relations can be easily set using treeviews with checkboxes in the AJAX Manager dialog:
RadAjax for ASP.NET AJAX 6

The other advantage of the AJAX Manager is that it serves as a centralized place for management of the
AJAX relations (Section 2.4).

2.2  Intuitive Way for Defining AJAX Relations


When using ASP.NET AJAX out-of-the-box you need to set triggers in order to define the AJAX behavior of the
page (which controls initiate AJAX requests and which controls are respectively updated). This approach,
however, presents an inconvenience because the AJAX relations are defined in a way that's reverse to the
users' natural interaction with the application interface.
Consider we have the following AJAX relation:
 When the calendar is clicked the e-mail list and the message body need to be updated

This represents the actual sequence in which the user will interact with the application - he/she will click a day
on the calendar and as a result the e-mail list and the message body will be updated.

However, when using triggers you will have to define this scenario in the opposite way - which element has to
be updated as a resuit of another element being clicked. So for the above AJAX relation you will have to set 2
triggers.
 "Message Body" Callback Panel - Trigger 1: The message body needs to be updated when the calendar
is clicked
 "E-mail list" Callback Panel - Trigger 2: The e-mail list needs to be updated when the calendar is
clicked
RadAjax for ASP.NET AJAX 7

As you can see, the combination of 2 triggers define one AJAX relation. Moreover, they are defined in the
reverse direction, which can be a significant challenge when AJAX-enabling complex real-life applications like
the Telerik HelpDesk sample (http://www.telerik.com/helpdeskbeta), which will probably need 20+
UpdatePanels and numerous triggers.

Telerik RadAjax for ASP.NET AJAX offers a much more intuitive way for setting AJAX relations, which follows
the users' natural interaction with the application interface.

Consider we have to implement the same AJAX relation:


 When the calendar is clicked the e-mail list and the message body need to be updated

To do this we need to open the AJAX Manager dialog and use the checkboxes to define the following:
RadAjax for ASP.NET AJAX 8

1. Set the calendar (Calendar1 control) as a control that will initiate AJAX requests
2. Set the e-mail list (EmailGrid control) and the message body (MessageBody control) as controls that
need to be updated after the respective AJAX request (in our case initiated by the calendar)

This approach is much more convenient and gives you an "at-a-glance" picture of the various AJAX relations
and the elements that comprise them. To extract this information otherwise would require that you go over all
Triggers and draw something like a "Trigger diagram".

Last but not least the Telerik RadAjax framework offers a completely Codeless Development (Section
2.3) experience.

2.3  Codeless Development


Telerik RadAjax for ASP.NET AJAX leverages the Microsoft ASP.NET AJAX framework to offer a completely
codeless development experience when building AJAX-enabling applications. The patent-pending Click-and-
Go™ technology allows you to define all AJAX relations on the page (which controls initiate AJAX requests
and which controls are respectively updated) using a single dialog. No other modification to your application
will be necessary and not a single line of client- or server-side code will need to be written.
RadAjax for ASP.NET AJAX 9

In contrast, other AJAX frameworks offer simply a generic callback initiating control. From there on you have
to manually write custom JavaScript functions that call the "callback" method of this control, and attach the
JavaScript functions to the various events of the controls that you need to AJAX enable.
Consider you need to AJAX-enable the standard ASP.NET calendar. This control renders a __doPostBack()
functions for every day of the current month as well as for the previous- and next-month buttons. So you will
generally have to do the following:
 write a custom JavaScript function that calls the "MakeCallback" method of the generic callback control
with the respective parameters
 override the DayRender event of the calendar so that for each day you call the this custom JavaScript
function instead of the __doPostBack function of the calendar
 since the SelectionChanged event of the calendar will not be fired, you have to move the server-side code
that is executed on SelectionChanged event of the calendar to the "Callback" server event of the generic
callback control

Now think about complex real-life applications with numerous controls and AJAX relations, like the Telerik
HelpDesk sample (http://www.telerik.com/helpdeskbeta). Implementing AJAX in the above
mentioned manner will be if not impossible then definitely not worth the efforts. Moreover, this approach will
break the ASP.NET page lifecycle, which can cause problems to your application.
RadAjax for ASP.NET AJAX 10

2.4  Centralized Management of AJAX Relations


A typical challenge when using ASP.NET AJAX is the fact that the AJAX behavior of the page (which controls
initiate AJAX requests and update other controls) is achieved by setting numerous controls individually.
For example, in certain frameworks you need to triggers that initiate AJAX callbacks upon predefined
conditions. For example:
 "Message Body" UpdatePanel - Trigger 1: The needs to be updated when an e-mail item is clicked
 "Message Body" UpdatePanel - Trigger 2: The needs to be updated when the calendar is clicked
 "E-mail list" UpdatePanel - Trigger 1: The needs to be updated when the calendar is clicked

The combination of these 3 Triggers define the 2 AJAX relations on the page, which are:
1. When the calendar is clicked the e-mail list and the message body need to be updated
2. When an e-mail message is clicked the message body only needs to be updated

As you can see, it is not very easy to figure out what will be the effect of the combination of triggers, especially
when you have complex real-life applications like the Telerik HelpDesk sample
(http://www.telerik.com/helpdeskbeta). This task would require placing 20+ Update Panels and setting
numerous triggers.
Moreover, setting several triggers that facilitate every of the numerous AJAX relations will definitely need
serious planning and probably something like a "Trigger diagram".
RadAjax for ASP.NET AJAX 11

In contrast, the Telerik RadAjax framework offers a centralized place where you can define and modify the
AJAX relations on the page. This is done through the single configuration dialog of the AJAX Manager in
Visual Studio .Net design mode.
If we need to implement the above scenario we need to simply set the two relations in the dialog.
Relation 1: When the calendar is clicked the e-mail list and the message body need to be updated
RadAjax for ASP.NET AJAX 12

Relation 2: When an e-mail message is clicked the message body only needs to be updated

It is clearly of benefit for developers to be able to see all AJAX relations at a glance in one centralized place (the
AJAX Manager dialog) , rather than having to configure every Trigger of every UpdatePanel individually.

The logic for setting AJAX relations in the AJAX Manager dialog leads to another benefit - the AJAX relations
are defined in the same sequence in which users interact with the interface of the application. For more
information see section "Intuitive Way for Defining AJAX Relations (Section 2.2)".
RadAjax for ASP.NET AJAX 13
RadAjax for ASP.NET AJAX 14

3  Getting Started
3.1  How RadAjax Works: Controls And Configuration
No matter which control you would chose (RadAjaxManager or RadAjaxPanel ('Manager vs. Panel'
in the on-line documentation)) the application should function properly with regular postbacks in order
to be AJAX-enabled as expected.
The only difference is the AJAX requests update a portion of the page only -- the portion surrounded by
RadAjaxPanel or set as updated in RadAjaxManager settings. Read more about the AJAX technique in the
Introduction topic here (Section 1.1).

RadAjax simply converts the regular postbacks into AJAX updates.

Therefore, one cannot ajaxify controls, which does not perform regular postbacks (for example CheckBoxes,
DropDowns, TextBoxes require AutoPostBack property to be set to true to be able to post back to the
server).

Always make sure the control postbacks when you to try to ajaxify it.

In general, should one get an error, the first step in troubleshooting the problem would be to set
EnableAJAX RadAjaxControl property to false. This will disable AJAX temporary.
The following troubleshooting articles briefly explain common errors and mistakes:
Known reasons for error messages (Section 11.1)
Most common mistakes (Section 11.2)

A brief description of the AJAX controls follows:

RadAjaxPanel
The Panel control mimics the behavior of ASP:UpdatePanel control - all the postbacking controls
surrounded within start performing AJAX updates. Read more about the RadAjaxPanel here (Section 6.1).

RadAjaxManager
The Manager purpose is to configure the necessary AJAX settings specifying the AJAX initiators and updated
controls. The AJAX initiator (ajaxified control) is the one which would perform the AJAX request updating the
respectively set controls. Find how to configure the AJAX Manager control in the following articles:
AJAX Manager setup (Section 5.1)
AJAX-enabling an application through RadAjaxManager and RadAjaxLoadingPanel controls
(Section 3.3)

RadAjaxManagerProxy
Similar to the AJAX Manager control, the Manager proxy is an additional option to configure the necessary
AJAX settings completely design-time. The Manager proxy control is widely used in WebUserControl or
Master/ContentPage scenarios:
RadAjaxManagerProxy control (Section 7.1)
RadAjax and WebUserControls (Section 5.2.2)
RadAjax and MasterPage scenarios (Section 5.2.3)
RadAjax for ASP.NET AJAX 15

RadAjaxLoadingPanel
The LoadingPanel is displayed over or above the updated controls during AJAX updates. Read how to use and
configure the LoadingPanel control here (Section 8.1).

3.2  Design Time of RadAjax Controls


Display Smart Tags by right clicking the control and choosing Show Smart Tag from the context menu, or
clicking the small rightward-pointing arrow located in the upper right corner of the control.
The Smart Tags for RadAjaxPanel (ajxRadAjaxPanelOverview.html) and RadAjaxManager
(RadAjaxManagerOverview.html) are nearly identical. The RadAjaxManager Smart Tag differs from the
RadAjaxPanel version in that it has a Configure Ajax Manager (DesignPropertyBuilder.html) link and
a "Choose DefaultLoadingPanelID" drop down list instead of "Choose LoadingPanelID". RadAjaxPanel also
has a Add RadAjaxManager option.

RadAjaxPanel

General Features
 Enable AJAX: When this item is checked, all requests for controls within the RadAjaxPanel are handled
via AJAX. If not checked, requests are handled in the legacy postback manner.
 Enable AJAX History: When checked, browser history is enabled even when using AJAX. The forward
and back buttons of the browser work as expected in a standard postback web site.
 Enable update of Page <head> element: If this option is checked, the Page <Head> element can be
modified during AJAX updates.
 Choose LoadingPanelID: Select a RadAjaxLoadingPanel
(RadAjaxLoadingPanelOverview.html) instance from the drop down list to display during AJAX
updates.
RadAjax for ASP.NET AJAX 16

The Enable AJAX History feature currently works for Internet Explorer only.

Ajax Resources
 Add RadAjaxManager...:Adds a RadAjaxManager component to the form.
 Replace ScriptManager with RadScriptManager: Replaces the Microsoft Script Extensions
ScriptManager with RadScriptManager. RadScriptManager provides enhanced capabilities for handling
web resources and combining scripts for better performance.
 Add RadStyleSheetManager: Adds a RadStyleSheetManager to the web page. RadStyleSheetManager
provides enhanced capabilities for handling web resources and combining stylesheets for better
performance.

Learning Center
 Links navigate you directly to examples, help, and code library.
 You can also search the Telerik web site for a given string.
 You can navigate directly to the Telerik Support Center
(http://www.telerik.com/support/home.aspx).

RadAjaxManager

Configure Ajax Manager: Displays the RadAjaxManager Property Builder


(DesignPropertyBuilder.html).

General Features
 Enable AJAX: When this item is checked, all requests for controls managed by the RadAjaxManager
(RadAjaxManagerOverview.html) are handled via AJAX. If not checked, requests are handled in the
legacy postback manner.
 Enable AJAX History: When checked, browser history is enabled even when using AJAX. The forward
and back buttons of the browser work as expected in a standard postback web site.
 Enable update of Page <head> element: If this option is checked, the Page <Head> element can be
RadAjax for ASP.NET AJAX 17

modified during AJAX updates.


 Choose DefaultLoadingPanelID: Select a RadAjaxLoadingPanel
(RadAjaxLoadingPanelOverview.html) instance from the drop down list to display during AJAX
updates.

The Enable AJAX History feature currently works for Internet Explorer only.

Ajax Resources
 Add RadAjaxManager...:Adds a RadAjaxManager component to the form.
 Replace ScriptManager with RadScriptManager: Replaces the Microsoft Script Extensions
ScriptManager with RadScriptManager. RadScriptManager provides enhanced capabilities for handling
web resources and combining scripts for better performance.
 Add RadStyleSheetManager: Adds a RadStyleSheetManager to the web page. RadStyleSheetManager
provides enhanced capabilities for handling web resources and combining stylesheets for better
performance.

Learning Center
 Links navigate you directly to examples, help, and code library.
 You can also search the Telerik web site for a given string.
 You can navigate directly to the Telerik Support Center
(http://www.telerik.com/support/home.aspx).

RadAjaxManagerProxy

Configure Ajax Manager: Displays the RadAjaxManager Property Builder


(DesignPropertyBuilder.html).

RadAjaxLoadingPanel

General Features
 Is Sticky: If this option is checked, the panel will appear where you have placed it on your webform. If
the option is not checked, the loading panel will appear in the place of controls being updated. The option
is unchecked by default.
 Initial Delay Time: Specifies the delay in milliseconds, after which the loading panel will be shown.
 Min Display Time: Specifies the minimum time in milliseconds that the loading panel will be shown.
 Transparency: Is a value from 0 to 100 that indicates the transparency of the loading panel. A value of 0
will make the loading panel completely opaque and larger values will display the loading panel
progressively more transparent.
RadAjax for ASP.NET AJAX 18

3.3  Getting started: AJAX-enable a scenario through


RadAjaxManager and LoadingPanel
The following demonstrates the basic steps required to Ajax-enable an an application using
RadAjaxManager and AjaxLoadingPanel. RadAjaxManager can be added to any web application that
requires the replacement of ordinary post backs with ajax requests. Ajax-enabling through RadAjaxManager
is a completely codeless process. AjaxLoadingPanel is also used to enhance the user experience.
AjaxLoadingPanel supports image templates, which can be displayed as progress indicators whenever a
callback request is performed, i.e. when the page is loading.
1. To use RadAjaxManager drag it from the toolbox to the design surface.

2.
3. Drag and drop a AjaxLoadingPanel from the toolbox to the design surface.
RadAjax for ASP.NET AJAX 19

4. To Ajax-enable the individual controls on the page, configure RadAjaxManager through the “Configure
Ajax Manager” link of the Smart Tag. Again, this step is completely codeless, requiring only design-time
configuration of the necessary relations between the AJAX Manager and the other controls:
RadAjax for ASP.NET AJAX 20

5. On the left-hand side are controls that will initiate Ajax requests. On the right-hand side are controls that
will be updated via Ajax. Include and exclude items from these lists via the checkboxes to the left of each
control name:

6. A loading panel can be displayed for each control that will be updated via the Ajax Manager. Set the
LoadingPanelID property to the ID of an existing Loading Panel:
RadAjax for ASP.NET AJAX 21

7. The screenshot below shows how the Ajax-enabled application looks at run-time. The upper button,
located between the two List Boxes, adds an artist’s name to the right-hand side List Box control. With the
help of the AJAX Manager, the normal post back is replaced by a callback. The loading panel displays in
the currently updating control:

3.4  Server-Side OverView


RadAjaxPanel and RadAjaxManager both descend from RadAjaxControl that introduces several
common members that control and respond to AJAX updating behavior:
 Properties (ServerProperties.html)
 Methods (server-methods.html)
 Events (Section 14.6)

Here are properties that are specific to each control:

RadAjaxPanel Specific Properties


 LoadingPanelID: The ID for the RadAjaxLoadingPanel to display during AJAX updates.

RadAjaxManager Specific Properties


 DefaultLoadingPanelID: The ID for the RadAjaxLoadingPanel to display during AJAX updates if no
loading panel is specified in the AjaxSettings (telerik.web.ui-telerik.web.ui.ajaxsetting.html) .
RadAjax for ASP.NET AJAX 22

4  Changes and backward compatibility


4.1  RadAjax for ASP.NET vs RadAjax for ASP.NET AJAX
RadAjax for ASP.NET vs. RadAjax
Just like any other product in the new RadControls for ASP.NET AJAX, RadAjax will be the successor of
RadAjax for ASP.NET. The new edition consists of the same controls (RadAjaxManager, RadAjaxPanel, and
RadAjaxLoadingPanel) however is implemented according to the new technology. The major characteristics of
RadAjax are the following:
 Built on top of Microsoft ASP.NET AJAX, using its programming model
 Uses the Microsoft ASP.NET AJAX engine, not the Telerik proprietary AJAX engine
 Supports only .NET 2.0 framework, while the current RadAjax supports 1.x as well
 Will include new features and performance optimizations, made possible by the underlying Microsoft
ASP.NET AJAX framework
 Backwards compatible with RadAjax for ASP.NET (requires minor changes)
 Seamlessly interoperates with all other RadControls for ASP.NET

Backwards compatibility
A top goal in the development of RadAjax was to maintain backwards compatibility. This was an extremely
difficult task, yet we are happy to announce that our efforts were successful. As a result, RadAjax for ASP.NET
and RadAjax are completely interchangeable on their main features.
RadAjax can update:
 all controls from RadControls for ASP.NET
 all controls from RadControls
 all standard ASP.NET controls and most 3rd party controls

Similarly, the RadAjax for ASP.NET can update the same types of controls:
 all controls from RadControls for ASP.NET
 all controls from RadControls
 all standard ASP.NET controls and most 3rd party controls

The syntax, controls names, etc. of the new RadAjax is identical to the one of RadAjax for ASP.NET, just the
namespace is different. This makes the process of migration (read below whether you should migrate at all)
becomes more or less a matter of tag-name global replace.
If you consider migration of existing projects to the new RadAjax you need to perform 3 easy steps:
 Install Microsoft ASP.NET AJAX if you haven’t already done so and make the required web.config
modifications
 Add the RadAjax registration directive (or just drag-and-drop the control from Visual Studio toolbox onto
your
 webform)
 Global replace the old tag names (e.g. rada:RadAjaxManager) with the new tag names (e.g.
telerik:RadAjaxManager)

This is all you have to do – no other modifications or “migration” of your code is necessary. You don’t even
have to remove RadAjax for ASP.NET from your project if you don’t want to, as it will do no harm. The above
steps are described in details in the RadControls documentation.
RadAjax for ASP.NET AJAX 23

What is the future of RadAjax for ASP.NET?


As explained before, the release of RadControls for ASP.NET AJAX will not affect Telerik’s support for the
existing RadControls for ASP.NET. Although new controls will be only added to , all existing controls will
continue to be enhanced with new features throughout 2007. It be noted that the new releases of the classic
ASP.NET controls will not be mirror versions of their counterparts, as there are features which will be very
hard or impossible to implement due to the underlying architectural differences in the two suites.
In 2008, RadControls for ASP.NET AJAX will be officially launched and existing RadControls will only receive
bug fixes and minor enhancements. The products will be fully supported, though, through at least 2010, after
which only “extended support” for the RadControls for ASP.NET will be offered.
In many cases customers do not have to migrate existing applications, since the current controls are pretty
much feature complete, stable, and work fine. This is particularly valid for RadAjax.
We would like to note that we are open to changes based on the feedback we get from the community. Our #1
goal is to serve you well and we will act according to the needs of the greater part of the community.

Do I have to migrate RadAjax to RadAjax in my old applications?


For most customers with existing application the answer is “No ”, because:
 RadAjax for ASP.NET is stable and feature complete.
 It will continue to receive updates and bug-fixes.
 The support team will continue to answer tickets related to the current RadControls suite, after is officially
released in early 2008.
 The two suites can be used together, or in other words, you can add new controls available only in the
suite to existing applications, without having to change/migrate anything else.
 RadAjax for ASP.NET can update both the current and the new controls. As a result you don’t have to
migrate RadAjax if you just need to add a new control to your application.
 If you have a .NET 1.x application, you need to stick with the current RadAjax for ASP.NET, since only
work on .NET 2.0.

The migration to RadAjax can be gradual and you can also use both current and new RadAjax in the same
application even on the same page. They can coexist without any problems

What shall I use for new applications?


If you are building new applications, we suggest that you start using the new because:
 It will be introducing new features and optimizations, made possible by the underlying ASP.NET AJAX
framework
 It can interoperate with the current RadControls for ASP.NET, which do not yet have counterparts
 It is provided with a “Go live” license and will be fully supported, while it is in Beta.

Although backwards compatibility issues are possible, they are very unlikely. Yet we suggest that you spend
enough time experimenting and field-testing the new controls before jumping in all-out production
implementations.

4.2  What's New in RadAjax for ASP.NET AJAX


Q2 2008 release
There is not any new functionality implemented for RadAjax for the Q2 2008 release of the product. Merely
enhancements, optimizations and bugfixes are included.

Q1 2008 release
 AJAX request queueing:
RadAjax for ASP.NET AJAX 24

The subsequent requests are ignored in ASP.NET AJAX by default while the response is not received. RadAjax
now implements the AJAX request queueing mechanism, which is turned off by default. Use
RequestQueueSize property of RadAjaxManager and RadAjaxPanel to enable the functionality. Value of 2
for example means 2 requests will be queued. More info is available in this help topic (Section 10.11).
 Due to the changed layout in some scenarios with RadAjaxManager involved, there is a new property
namely UpdatePanelRenderMode. Read more about it in this topic (Section 5.3.4) .

Q3 2007 release
RadCodeBlock is a control that is used to wrap code blocks in your aspx, which will normally throw the famous
"Controls collection cannot be modified ..." error when MS AJAX is present on the page.
RadScriptBlock is a control similar to RadCodeBlock and you can use it to execute scripts blocks inside the
updating areas. Example:
Example Title
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
alert(1);
</script>
</telerik:RadScriptBlock>

21st of May, 2007

The new release of RadAjax for ASP.NET AJAX includes the following features:

 RadAjaxManagerProxy control

Similar to ASP.NET AJAX ScriptManager


(http://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspx)/
ScriptManagerProxy (http://www.asp.net/learn/videos/view.aspx?tabid=63&id=95), RadAjax
Manager/Proxy couple is also available. Placing a single manager on the main/master page, one can add a
proxy instance in the user control/content page and configure/add the necessary settings design-time
within the user control/content page, instead of adding them programmatically (finding the manager from the
main page/master page at the code-behind).

RadAjaxManagerProxy 'forwards' the necessary AJAX relations to the manager instance. It does not work
independently!
Read more about RadAjaxManagerProxy control on this topic (Section 7.1) as well as about the
MasterPages/WebUserControls scenarios here (Section 5.2.3) and here (Section 5.2.2). Todd Anglin
summarizes the manager proxy info at his blog here
(http://blogs.telerik.com/blogs/todd_anglin/archive/2007/05/24/new_best_practice_ajaxifying_usercon
 New events - AjaxSettingCreating/AjaxSettingCreated server-side.

The new RadAjaxManager events allow accessing AJAX initiator, updated control and update panel created for
that particular setting runtime. One can perform custom logic like updating only specific controls depending
on the initiator or updated control. AjaxSettingCreating event is cancelable.

23rd of April, 2007


The first release of RadAjax for ASP.NET AJAX includes a new feature, which is not implemented in the
regular RadAjax for WebForms suite: Support of Back and forward browser buttons (Browser history)
(more info here (Section 4.5)).
RadAjax for ASP.NET AJAX 25

4.3  Changes and backwards compatibility


Telerik RadAjax for ASP.NET AJAX Q2 2008

RadAjax for ASP.NET AJAX which is part of the Q2 2008 release is fully backwards compatible with its
previous version (Q1 2008).

Telerik RadAjax Q3 2007 --> Telerik RadAjax Q1 2008

1) Client-side API

The compatibility layer which was used in the transition beta period is now removed. All client-side methods
strictly follow the ASP.NET AJAX conventions and are lower case. For instance:
 ajaxRequest(eventArgs)/ajaxRequestWithTarget(sender, eventArgs) should always be used from now on
(methods/events start with lower case letters)
 AjaxRequest(eventArgs)/AjaxRequestWithTarget(sender, eventArgs) are no longer supported.

This also results in significant improvement in page loading times.

2) Client-side validation
Client-side validation is now supported only under full trust. Support for medium trust is missing at this time.

3) Full DNN support


RadAjax for ASP.NET has some limitations when running in medium trust. To make it work you should
change the base type of your pages that use radjax from "System.Web.UI.Page" to
"Telerik.Web.UI.RadAjaxPage". However DNN module controls Inherit from
Entities.Modules.PortalModuleBase and thus you cannot simply change the page's base class. For such cases
you should use the new property RestoreOriginalRenderDelegate. By default it is true, if you work in
DNN or medium trust, you should set that to false.

4) Full Ajax control extender support


Previously there were some problems with certain extenders under certain conditions. These problems have
been fixed.

Telerik RadAjax Q2 2007 --> Telerik RadAjax Q3 2007

All fields with uppercase naming are now obsolete. Please use the new changed fields to reflect the client-
side model based on the MS AJAX framework e.g.: this.AjaxSettings --> get_ajaxSettings()

1) Assembly and namespace changes


Due to the changes in assembly and namespace's name, you need to change the Register directive to point to
Telerik.Web.UI instead of Telerik.Web.Controls. Here is how it should look now:
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
The same change affects the code-behind - where you have
using/Imports Telerik.Web.Control
you have to change it into
using/Imports Telerik.Web.UI

2) ScriptManager control
RadAjax for ASP.NET AJAX 26

There must be always an ASP:ScriptManager control placed on the page before the RadAjax controls. Here
is a sample code:
<asp:ScriptManager ID="ScriptManager" runat="server" />
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Panel2"></telerik:AjaxUpdatedContr
<telerik:AjaxUpdatedControl ControlID="Label1"></telerik:AjaxUpdatedContr
<telerik:AjaxUpdatedControl ControlID="Panel1"></telerik:AjaxUpdatedContr
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>

3) RadAjaxLoadingPanel class
The old AjaxLoadingPanel class is renamed to RadAjaxLoadingPanel. You need to change the source as
follows:
<telerik: RadAjaxLoadingPanel ID="LoadingPanel1" runat="server">
Loading content ...
</telerik: RadAjaxLoadingPanel>

4) Only one instance of RadAjaxManager control is supported


The previous limitation of single RadAjaxManager per naming container is extended so that now there
should be only one instance of the control on the whole page. This means that you cannot have one manager
on the main page containing a user control and another inside the user control itself (or Master and content
page). Otherwise an error is thrown.
Instead, having a manager instance on the main page/MasterPage, one can already add a
RadAjaxManagerProxy in the user control/content page. The Proxy control purpose is similar to the one of
ScriptManagerProxy (http://www.asp.net/learn/videos/view.aspx?tabid=63&id=95) and it could
be used to add the necessary settings design-time within the user control/content page, instead of
adding them programmatically finding the manager from the main page/master page.
Additionally, if one still needs the manager instance at the code of a WebUserControl for example, she can get
the manager by RadAjaxManager.GetCurrent() method call. The method will return null if there is no
manager on the page, similar to ASP:ScriptManager implementation
(http://ajax.asp.net/docs/tutorials/assignScriptReferences.aspx).

5) Client-Side events OnRequestSent and OnResponseReceived missing


Those events will not be implemented in RadAjax for ASP.NET AJAX as they are no longer needed.

6) Server code blocks in form script tag


Any code blocks (i.e. <% ... %>) on the page like the following:
<script language="javascript" type="text/javascript">
function AjaxReq(args)
{
$find( "RadAjaxPanel1").ajaxRequestWithTarget( "<%= Button1.UniqueID %>", '');
}
</script>
must be wrapped inside the RadCodeBlock control (Section 15):

<telerik:RadCodeBlock ID="cb1" runat="server">


RadAjax for ASP.NET AJAX 27

<script language="javascript" type="text/javascript">


function AjaxReq(args)
{
$find( "RadAjaxPanel1").ajaxRequestWithTarget( "<%= Button1.UniqueID %>", '');
}
</script>
</telerik:RadCodeBlock>
otherwise a server error is thrown: System.Web.HttpException: The Controls collection cannot be modified
because the control contains code blocks (i.e. <% ... %>).
Why is adding RadCodeBlock necessary?
The way code blocks are implemented in ASP.NET may interfere with ajax manager's render interception
mechanism. That is why we have created the workaround of enclosing those code blocks in a RadCodeBlock
control. Wrapping the blocks within a RadCodeBlock control will isolate the effects to that control only and the
partial rendering code will not be affected.

7) Adding AJAX settings dynamically in Page_Init event is no longer supported


Use Page_Load/PreRender instead. More info about adding the AJAX settings dynamically is available here.

8) RadAjaxNamespace and AjaxNS are no longer available.


In case they've been used in a client script to access RadAjax controls, those should be get via $find
("RadAjaxLoadingPanel1") pattern.

9) UpdatedControlsEventArgs class renamed to AjaxUpdatedControlsEventArgs


The arguments class of ResolveUpdatedControls event has been renamed.

10) Showing/Hiding controls with ajax


This scenario works properly with the new RadAjaxManager, while a workaround with always visible control
on the page was required for the previous version

11) ResolveUpdatedControls event is no more supported


The ResolveUpdatedControls event has been removed from the RadAjax for ASP.NET AJAX as it no longer
serves its purpose. Initially created for handling scenarios in which the initiator of the ajax request is removed
from the page, then was extended to handle AjaxSettings modifications in runtime. The event is now
superseded by the AjaxSettingCreating event (Section 14.3).

4.4  Current RadAjax Limitations


Find below a list of all know limitations of the new RadAjax compared to the old versions:

1) ASP Standard Validators


Although ASP Standard Validators on the client are officially not supported (see "Controls that are not
compatible with UpdatePanel controls" in ajax.asp.net docs here
(http://ajax.asp.net/docs/overview/UpdatePanelOverview.aspx)), we found a way to make them
work with our RadAjax controls. The only limitation is that they would work only in Full Level trust
environments (i.e would not work on shared hostings). For shared hostings, please use server validation by
setting the EnableClientScripts property of the validators to false.

2) Response.RedirectLocation on AJAX update


This is the third limitation "inherited" from ASP.NET AJAX. Response.Redirect could be used instead.
RadAjax for ASP.NET AJAX 28

3) RadAjaxTimer control
We decided not to include a Timer control in RadAjax for ASP.NET AJAX. This is due to the fact that the timer
control is a postback control and does not include ajax capabilities by itself. The second reason is that a timer
control is already included in MS AJAX that offers the basic functionality we did.

4) Ajaxified control postbacks when having no updated controls


For example the following RadAjaxManager setting will not ajaxify the button:
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
You can work around that by adding a control to be updated. For example - the same AJAX initiator control:
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Button1" />
</UpdatedControls>

5) RadAjaxManager and RadAjaxPanel at the same application


There are some known issues when using both the manager and the panel in some complex applications -
MasterPage or WebUserControls. However, note that a single RadAjaxManager (and no panels) in the
master/main page could handle all the scenarios.

6) Client-Side events OnRequestSent and OnResponseReceived missing


Those events are removed in RadAjax for ASP.NET AJAX. There is no way to "simulate" them due to the way
ASP.NET AJAX works. Please use OnRequestStart and OnResponseEnd for your needs.

7) Various controls not supported by the MS AJAX framework


See a full list of controls, not compatible with RadAjax for ASP.NET AJAX here (Section 10.6).

4.5  Back and Forward browser buttons (browser history)


Generally speaking, the ajax controls are using xmlhttp requests which update silently parts of the page. The
browser Back and Forward functionality is only available when a full postback has occurred and that is the
reason for them not to remember the last page state after ajax request.
Currently this limitation has been addressed (for IE only), but our devs are researching on the matter and we
hope to provide a solution for Gecko-browsers soon as well. You can however use the History control by
Nikhil Kothari (http://www.nikhilk.net/UpdateControls.aspx) which should work seamlessly with
our control. Note that the history control requires you to manually add history links and is not handled out of
the box by the MS AJAX framework.
RadAjax for ASP.NET AJAX 29

5  RadAjaxManager Control
5.1  AJAX Manager
AJAX Manager is one of the two major controls of the Telerik RadAjax suite. The other one is AJAX Panel
(Section 6.1). AJAX Manager allows developers rapidly develop powerful and complex AJAX solutions.
The main features of AJAX Manager are:
 You can ajaxify all controls that normally work with postbacks.
 Defines visually and codeless (in Visual Studio design-time) which elements should initiate AJAX requests
and which elements should be updated
 No need to modify your application logic
 Allows you to update a number of page elements at once regardless of their position on the page.
 No need to write any JavaScript or invoke AJAX requests manually

Using a single AJAX Manager on the page you can create complex web applications like Microsoft Outlook
® Web Access portal.
The visual designer of AJAX Manager, accessible in VisualStudio, lets you set even the most complicated
update scenarios such as:

A single control to update one or more controls with an AJAX


1 updates 2 and 3
request:

A second control to update other controls (or even controls from


3 updates 2 and 5
the previous scenario) with an AJAX request:

6 updates 6 (i.e.
A control to update itself with an AJAX request:
itself)

Using the AJAX


Call the AJAX Manager API from a control on the page and manager API,
update control(s) on the page 2 is made to update
1 and 4

In order to use AJAX Manager, you need to drag it from the VisualStudio toolbox to your page.

Note that you can't have two AJAX Managers in a single page. In case of MasterPage or
WebUserControl, the best option is to use single AJAX Manager on the master/main page.

5.1.1
Setting the control relations in Property Builder
AJAX Manager comes with a visual builder for setting the relations between the AJAX request initiator and
the controls that will be updated. You can start the property builder by right-clicking the control and choosing
the Configure Ajax Manager command in the control's smart tag.
The property builder is pretty intuitive and simple to use. The tool has three panes:
1. The left pane is a treeview with all controls on the page. Select a control that will initiate the callback
request. Only the controls that have their check-boxes checked will initiate callbacks. Once you select the
control in this pane, you need to choose the controls that will be updated. This can be done in the middle
pane.
2. The middle pane is another treeview with all controls on the page. Here you can select which controls will
be updated after a callback request from the control checked and selected in the left pane.
Please note that your selection in the middle pane can be applied only to one control from the left
pane. Thus you can have different sets of controls that will be updated depending on the callback initiator
RadAjax for ASP.NET AJAX 30

control (from the left pane). After you set the controls that will be updated, you may select a Loading
panel for each one of them. The Loading panel is set in the right pane.
3. The right pane lets you specify the Loading panel that will be used for the controls selected in the middle
pane. Each control that will be updated can have a separate Loading panel set. A default loading panel
could be set as well through DefaultLoadingPanelID property of RadAjaxManager control. If it is used,
there is no need to set the loading panel on each new AJAX setting - the default loading panel will be
automatically applied everywhere.

You can find the working example of the screenshot below here (http://localhost/Telerik/Telerik%
20RadAjax1.0_NET2/AJAX/Examples/Manager/FirstLook/DefaultCS.aspx) here
(http://localhost/Telerik/Telerik%
20RadAjax1.0_NET1/AJAX/Examples/Manager/FirstLook/DefaultCS.aspx):

5.1.2 Setting the control relations in CodeBehind


You can set the relationship between ajaxified and updated controls on server-side as well. For this purpose
you need to use the AddAjaxSetting methods:

RadAjaxManager1.AjaxSettings.AddAjaxSetting(<ajaxified control>, <updated control>);


RadAjaxManager1.AjaxSettings.AddAjaxSetting(<ajaxified control>, <updated control>, <LoadingPanel>
RadAjax for ASP.NET AJAX 31

5.1.3 Client-side functions


You can make any external control to force AJAX Manager perform an AJAX request by calling manager's
client-side functions. When using this function the event target defaults to the RadAjaxManager instance.

You can construct the javascript function calls manually or alternatively use the server-side method
GetAjaxEventReference and have Telerik RadAjax generate the necessary code for you.

$find("<%=AjaxManager1.ClientID%>").ajaxRequest(arguments)
arguments The parameters, which the control had used when it raised the request
This function can be handled by the AjaxRequest event on the server.

The ajaxRequestWithTarget(eventTarget, eventArgument) function can be called to simulate a


postback/AJAX request send by other control with the specified UniqueID and specified arguments.

__doPostBack(eventTarget, eventArgument)
or
$find("<%=AjaxManager1.ClientID%>").ajaxRequestWithTarget(eventTarget,
eventArgument)
The control which should raise postback event. Otherwise if your control is in a
eventTarget
INamingContainer, you should use the control's UniqueID .
eventArgument This is optional argument for the event

When you set a control as eventTarget it will raise an AJAX request and will update the controls that it was
set to update in the property editor. This function can be handled by the correspondent event handler (i.e.
Button_Click) on the server.

5.2  How-To
5.2.1 Add AjaxSettings programmatically
In some cases you need to add AJAX pair dynamically (at runtime). You should always do this in a Page event
handler, which is executed each time during the page lifecycle (Page_Load, Page_PreRender) so that the
control could be ajaxified when the page is initially loaded.

Note that you need to assure that the controls that take part in the AJAX pair are available on the page!

You cannot add AJAX settings dynamically in Page_Init event. It is too early in the page lifecycle since
the AJAX Manager is not created yet.
The example below demonstrates how to ajaxify a Button dynamically to toggle the visibility of an Image:
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" >
</telerik:RadAjaxManager>
<asp:Panel ID="Panel1" runat="server" Height="95px">
<asp:Image ID="Image1" runat="server" ImageUrl="http://www.Telerik.com/images/Homepage/TelerikLogo.
</asp:Panel>
And in the code-behind:

[C#]
protected void Page_Load(object sender, EventArgs e)
{
RadAjaxManager1.AjaxSettings.AddAjaxSetting(Button1, Panel1, null);
}
RadAjax for ASP.NET AJAX 32

...
protected void Button1_Click(object sender, EventArgs e)
{
Image1.Visible = !Image1.Visible;
}
[VB.NET]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
RadAjaxManager1.AjaxSettings.AddAjaxSetting(Button1, Panel1, Nothing)
End Sub
...
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Image1.Visible = Not Image1.Visible
End Sub

5.2.2 RadAjax and WebUserControls


RadAjax for ASP.NET AJAX Manager allows a single instance of the control on the same page only. One
cannot place manager in the main page and second instance inside a user control anymore. RadAjaxManager
designer on the other hand, cannot locate the WebUserControl (as well as controls inside it).
Since the release of RadAjax for ASP.NET AJAX from May 2007, there is a new, RadAjaxManagerProxy
control (Section 7.1). The new control can be added inside a WebUserControl and configured the same way
as the manager to AJAX-enable the user control completely codeless:

<telerik:RadAjaxManagerProxy ID="AjaxManagerProxy1" runat="server">


<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="DropDownList1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="DetailsView1" />
<telerik:AjaxUpdatedControl ControlID="GridView1" />
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="GridView1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="GridView1" />
<telerik:AjaxUpdatedControl ControlID="DetailsView1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManagerProxy>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />

RadAjaxManagerProxy can be used for design-time configuration only. It does not have a client-side
object, methods or events!

If one still needs the manager instance at the code of a WebUserControl for example so that an AJAX
request need to be triggered explicitly, she can get the manager by RadAjaxManager.GetCurrent()
method call. The method will return null if there is no manager on the page, similar to
ASP:ScriptManager implementation
(http://ajax.asp.net/docs/tutorials/assignScriptReferences.aspx).

Should you need the server or client-side RadAjaxManager functionality (like ResponseScripts collection,
ajaxRequest function) you can get the "master" manager instance via Server-Side GetCurrent method from
the user control code-behind:

RadAjaxManager GetCurrent method


RadAjax for ASP.NET AJAX 33

RadAjaxManager.GetCurrent(Page);

Use server-side code block in a JS function inside your WebUserControl to call the master manager
ajaxRequest function:
Accessing RadAjaxManager from WebUserControl's JavaScript
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function myUserControlClickHandler()
{
$find("<%= RadAjaxManager.GetCurrent(Page).ClientID %
>").ajaxRequest("content");
}
</script>
</telerik:RadCodeBlock>

As to the AJAX settings, the old RadAjax approach, adding AJAX settings programmatically, is still
applicable. Here is a simple example demonstrating how this could be achieved:
ASPX:
Main page:

<form id="Form1" method="post" runat="server">


<asp:ScriptManager ID="ScriptManager1" runat="server" />
<telerik:RadAjaxManager id="RadAjaxManager1" runat="server"></telerik:RadAjaxManager>
<uc1:WebUserControl1 id="WebUserControl1" runat="server"></uc1:WebUserControl1>
</form>

User Control:
<asp:Button id="Button1" Text="Button" runat="server"></asp:Button>
<asp:Label id="Label1" runat="server">Label</asp:Label>
And in the code-behind:
Main page:
[C#]

protected void Page_Load(object sender, EventArgs e)


{
//Get the WebUserControl
UserControl MyControl = (UserControl)Page.FindControl("WebUserControl1");

//Get user control's button and label


Button MyButton = (Button)MyControl.FindControl("Button1");
Label MyLabel = (Label)MyControl.FindControl("Label1");

//Add the necessary AJAX setting programmatically


RadAjaxManager1.AjaxSettings.AddAjaxSetting(MyButton, MyLabel);
}
[VB.NET]

Protected Sub Page_Load(sender As Object, e As EventArgs)


'Get the WebUserControl
Dim MyControl As UserControl = CType(Page.FindControl("WebUserControl1"), UserControl)

'Get user control's button and label


Dim MyButton As Button = CType(MyControl.FindControl("Button1"), Button)
Dim MyLabel As Label = CType(MyControl.FindControl("Label1"), Label)

'Add the necessary AJAX setting programmatically


RadAjaxManager1.AjaxSettings.AddAjaxSetting(MyButton, MyLabel)
End Sub 'Page_Load
RadAjax for ASP.NET AJAX 34

User control:

[C#]
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
[VB.NET]
Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles B
Label1.Text = DateTime.Now
End Sub

5.2.3 RadAjax and MasterPage


The controls in Telerik RadAjax suite can be used in various scenarios with MasterPage. However, one should
have in mind that she cannot have two RadAjaxManagers in master and content page at the same time.
Instead, since May 2007 release of , RadAjaxManagerProxy control can be added and configured
design-time the same way as the manager (Section 5.1).
Of course, one can add RadAjaxManager control in any ContentPage. Unfortunately not all possible
scenarios can be handled when using RadAjaxManager this way - for example a control in the master page
cannot be ajaxified. RadAjaxManager can handle only cases when there controls to ajaxify are beneath in
the manager control hierarchy, so we strongly recommend placing RadAjaxManager in MasterPage and
adding proxy controls in content pages.
Find below a RadAjaxManagerProxy within a content page example:
<telerik:RadAjaxManagerProxy ID="AjaxManagerProxy1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="DropDownList1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="DetailsView1" />
<telerik:AjaxUpdatedControl ControlID="GridView1" />
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="GridView1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="GridView1" />
<telerik:AjaxUpdatedControl ControlID="DetailsView1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManagerProxy>

RadAjaxManagerProxy control can be used for design-time configuration only. It does not have a client-
side object or methods!

Should you need the server or client-side RadAjaxManager functionality (like ResponseScripts collection,
ajaxRequest function) you can get the "master" manager instance via Server-Side GetCurrent method from
the ContentPage code-behind:

RadAjaxManager.GetCurrent (Page)

Use server-side code block in your JS function to call the master manager AjaxRequest function from the
ContentPage as well:
RadAjax for ASP.NET AJAX 35

<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">


<script type="text/javascript">
function myContentClickHandler()
{
$find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>").ajaxRequest("content");
}
</script>
</telerik:RadCodeBlock>

As to the AJAX settings, they still can be added programmatically - RadAjax controls can be accessed at
ContentPage's code-behind using FindControl method of MasterPage object. However, in case you use a
lot of ContentPages, you should write the same "finding" code in all the places. A better approach is to set the
Manager (and the Loading Panel if used) as a property and access it directly. You may refer to the following
forum thread from telerik asp-net-community where this approach is discussed (see Robert's code-snippet),
which is applicable to RadAjaxManager for ASP.NET AJAX as well:
http://www.Telerik.com/asp-net-community/forums/forum-thread.aspx?b311D=ebgbb

A live example with Telerik RadAjax and MasterPage can be found here:
http://www.telerik.com/demos/aspnet/prometheus/Ajax/Examples/Manager/MasterPage/DefaultCS.asp

5.2.4 MasterPages: ajaxify and update controls in master and


content page
With RadAjaxManager in your MasterPage you can ajaxify and update every single control in your application.
The example below shows how this could be achieved adding the necessary AJAX settings programmatically.
This sample application contains buttons in the the masterand content page. The two buttons update controls
in the master and content page as well. See the code below for details:

MasterPage aspx:
<telerik:radajaxmanager id="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="btnDecrease">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="TextBox1"></radA:AjaxUpdatedControl>
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:radajaxmanager>
<asp:LinkButton ID="btnDecrease" runat="server" OnClick="btnDecrease_Click">Decrease</asp:Lin
<asp:TextBox ID="TextBox1" runat="server">0</asp:TextBox>

<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">


</asp:contentplaceholder>

MasterPage C#:
protected void Page_Load(object sender, EventArgs e)
{
Label Label1 = (Label)ContentPlaceHolder1.FindControl("Label1");
RadAjaxManager1.AjaxSettings.AddAjaxSetting(btnDecrease, Label1);
}

protected void btnDecrease_Click(object sender, EventArgs e)


{
Label Label1 = (Label)ContentPlaceHolder1.FindControl("Label1");
Label1.Text = Int32.Parse(Label1.Text) - 1 + "";
RadAjax for ASP.NET AJAX 36

TextBox1.Text = Int32.Parse(TextBox1.Text) - 1 + "";


}

MasterPage VB:
Protected Sub Page_Load(sender As Object, e As EventArgs)
Dim Label1 As Label = CType(ContentPlaceHolder1.FindControl("Label1"), Label)
RadAjaxManager1.AjaxSettings.AddAjaxSetting(btnDecrease, Label1)
End Sub 'Page_Load

Protected Sub btnDecrease_Click(sender As Object, e As EventArgs)


Dim Label1 As Label = CType(ContentPlaceHolder1.FindControl("Label1"), Label)
Label1.Text = Int32.Parse(Label1.Text) - 1 + ""

TextBox1.Text = Int32.Parse(TextBox1.Text) - 1 + ""


End Sub 'btnDecrease_Click

Content page:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Button ID="btnIncrease" runat="server" Text="Increase" OnClick="btnIncrease_Click"
<asp:Label ID="Label1" runat="server" Text="0"></asp:Label>
</asp:Content>

Content page C#:


protected void Page_Load(object sender, EventArgs e)
{
RadAjaxManager AjaxManager = (RadAjaxManager)this.Master.FindControl("RadAjaxManager1"
AjaxManager.AjaxSettings.AddAjaxSetting(btnIncrease, Label1);

TextBox TextBox1 = (TextBox)this.Master.FindControl("TextBox1");


AjaxManager.AjaxSettings.AddAjaxSetting(btnIncrease, TextBox1);
}

protected void btnIncrease_Click(object sender, EventArgs e)


{
Label1.Text = Int32.Parse(Label1.Text) + 1 + "";

TextBox TextBox1 = (TextBox)this.Master.FindControl("TextBox1");


TextBox1.Text = Int32.Parse(TextBox1.Text) + 1 + "";
}

Content page VB:


Protected Sub Page_Load(sender As Object, e As EventArgs)
Dim AjaxManager As RadAjaxManager = CType(Me.Master.FindControl("RadAjaxManager1"), RadAjaxManager
AjaxManager.AjaxSettings.AddAjaxSetting(btnIncrease, Label1)

Dim TextBox1 As TextBox = CType(Me.Master.FindControl("TextBox1"), TextBox)


AjaxManager.AjaxSettings.AddAjaxSetting(btnIncrease, TextBox1)
End Sub 'Page_Load

Protected Sub btnIncrease_Click(sender As Object, e As EventArgs)


Label1.Text = Int32.Parse(Label1.Text) + 1 + ""

Dim TextBox1 As TextBox = CType(Me.Master.FindControl("TextBox1"), TextBox)


TextBox1.Text = Int32.Parse(TextBox1.Text) + 1 + ""
End Sub 'btnIncrease_Click
RadAjax for ASP.NET AJAX 37

5.2.5 MasterPages: initiating requests from one


ContentPlaceHolder and loading/updating controls in
another
RadAjaxManager could handle all the MasterPage and WebUserControls scenarios no matter the complexity of
the application. To prove this, we show you how it can handle a scenario, where loading of WebUserControls is
done in contents of MasterPage by RadAjaxManager.
An important point to notice in the following implementation, is the event bubbling approach. We use it
because we load dynamically a user control from an action in another loaded user control. So the button click
event is bubbled from the user control to the content page, where the first user control is loaded on each page
load. Then we determine whether to perform loading of the second user control depending on the command
from the button's bubbled event.
Here is the full working code containing a MasterPage, content page and two simple WebUserControls:

MasterPage ASPX:
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" />

<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">


</asp:ContentPlaceHolder>

<asp:Panel ID="Panel1" runat="server">


<asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
</asp:ContentPlaceHolder>
</asp:Panel>

This MasterPage has nothing in its code-behind.

Standard content page ASPX:


<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">


</asp:Content>

The key content page code-behind:

Private Function Content(ByVal id As String)


Return Page.Master.FindControl(id)
End Function

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me


'Load
Content("ContentPlaceHolder1").Controls.Add(LoadControl("~/Page1.ascx"))
Content("ContentPlaceHolder1").Controls(1).ID = "UserControl1"

'Get loaded user control's buttons


Dim AjaxButtonLoad As Button = CType(Content("ContentPlaceHolder1").FindControl("UserControl1
Dim AjaxButtonClear As Button = CType(Content("ContentPlaceHolder1").FindControl("UserControl

'Get the manager and the panel from the MasterPage


Dim AjaxManager As RadAjaxManager = CType(Content("RadAjaxManager1"), RadAjaxManager)
Dim MyPanel As Panel = CType(Content("Panel1"), Panel)

'Add the necessary AJAX settings - buttons update the panel in order to load the second user
AjaxManager.AjaxSettings.AddAjaxSetting(AjaxButtonLoad, MyPanel, Nothing)
RadAjax for ASP.NET AJAX 38

AjaxManager.AjaxSettings.AddAjaxSetting(AjaxButtonClear, MyPanel, Nothing)


End Sub

Protected Overrides Function OnBubbleEvent(ByVal source As Object, ByVal args As System.EventArgs


Dim commandArgs As CommandEventArgs = TryCast(args, CommandEventArgs)

'determine whether to load the user control depending on bubbled button command
If commandArgs IsNot Nothing Then
If commandArgs.CommandName = "Load" Then
Content("ContentPlaceHolder2").Controls.Add(LoadControl("~/Page2.ascx"))
Content("ContentPlaceHolder2").Controls(1).ID = "UserControl2"
ElseIf commandArgs.CommandName = "Clear" Then
'do nothing. the control won't be loaded anyway
End If
End If

Return MyBase.OnBubbleEvent(source, args)


End Function

First WebUserControl's code, which is loaded on each page load:


ASPX:
UserControl1
<asp:Button ID="btnLoad" runat="server" Text="Load" CommandName="Load" />
<asp:Button ID="btnClear" runat="server" Text="Clear" CommandName="Clear" />

Code-behind:
Public Event BtnClick As EventHandler

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLoad.


RaiseEvent BtnClick(sender, e)
End Sub

And the second WebUserControl, which is loaded when the button "Load" in the first WebUserControl is
clicked:
It just shows some text in the ASPX:
UserControl2

and have nothing in its code-behind.

5.2.6 Ajaxify particular templated GridView buttons


Sometimes you may want to ajaxify particular controls (residing in template column of GridView control) in
order to update other controls (for example outside of the GridView) without postback. The most straight-
forward solution is to ajaxify the whole GridView. Here is a sample code:

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


<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="GridView1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="GridView1" />
<telerik:AjaxUpdatedControl ControlID="TextBox" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
RadAjax for ASP.NET AJAX 39

However, you may need another column to make regular postbacks or even the rest of the actions to trigger
standard postback requests.
This is when the RadAjaxManager comes into place. The manager settings can be added programmatically
specifying each particular control which you want to ajaxify and/or update. The essential part is to attach the
appropriate event(s) in which to apply the ajax settings. For the GridView in this situation the proper place is
the Row_PreRender event handler.

The GridView in the sample contains one template and one button column. The ImageButtons in the template
column are ajaxified by the ajax manager and the buttons in the ButtonField start regular postbacks. Both the
image and the push buttons update text box outside of the GridView.

ASPX:

<asp:TextBox ID="TextBox1" runat="server" Width="400px" Text="not updated"></asp:TextBox>


<asp:ScriptManager ID="ScriptManager" runat="server"/>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
</telerik:RadAjaxManager>

<asp:GridView ID="GridView1" DataSourceID="AccessDataSource1" AllowPaging="true"


<Columns>
<asp:TemplateField HeaderText="TemplateField">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" CommandName="MyCommand" CommandArgumen
ImageUrl="arrow.gif" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" HeaderText="ButtonField" CommandName=
</Columns>
</asp:GridView>

<asp:AccessDataSource ID="AccessDataSource1" DataFile="~/Grid/Data/Access/Nwind.mdb"


SelectCommand="SELECT * FROM [Customers]"></asp:AccessDataSource>

C#:
protected void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
e.Row.PreRender += new System.EventHandler(Row_PreRender);
}
}

protected void GridView1_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs


{
TextBox1.Text = string.Format("CommandName:{0}, CommandArgument:{1}", e.CommandName, e.CommandArgume
}

protected void Row_PreRender(object sender, System.EventArgs e)


{
ImageButton ImageButton1 = ((ImageButton)(((Control)(sender)).FindControl("ImageButton1")));
RadAjaxManager1.AjaxSettings.AddAjaxSetting(ImageButton1, TextBox1);
}

VB:

Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.G


If e.Row.RowType = DataControlRowType.DataRow Then
AddHandler e.Row.PreRender, AddressOf Row_PreRender
End If
End Sub
RadAjax for ASP.NET AJAX 40

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.G


TextBox1.Text = String.Format("CommandName:{0}, CommandArgument:{1}", e.CommandName, e.Comman
End Sub

Protected Sub Row_PreRender(ByVal sender As Object, ByVal e As System.EventArgs)


Dim ImageButton1 As ImageButton = CType(CType(sender, Control).FindControl("ImageButton1"
RadAjaxManager1.AjaxSettings.AddAjaxSetting(ImageButton1, TextBox1)
End Sub

5.2.7 Update in composite control


This topic demonstrates a possible scenario of AJAX Manager updates controls from a composite control. It is
important to set IDs of instantiated controls as well as adding them into controls collection. A necessary AJAX
setting could be added at CreateChildControls method, however this must be done after controls are added
into corresponding controls collection.
The example below includes a single AJAX Manager control on the page. Here is the code-behind:

public partial class Default : System.Web.UI.Page


{
TestComposite Tst1;

protected void Page_Load(object sender, EventArgs e)


{
Tst1 = new TestComposite(RadAjaxManager1, "1");
//set an ID of instantiated control!
Tst1.ID = "tst1";
this.form1.Controls.Add(Tst1);
}

protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)


{
//Update control from the composite on AJAX request
Tst1.controLbl.Text = Tst1.controTB.Text;
}
}

And the composite control class:


public class TestComposite : CompositeControl
{
private Telerik.WebControls.RadAjaxManager m_radAm;
private string m_UniqueId;
public TextBox MyTxt;
public Label MyLbl;

public TestComposite(RadAjaxManager radAm, string UniqueId)


{
m_radAm = radAm;
m_UniqueId = UniqueId;
}

protected override void RecreateChildControls()


{
EnsureChildControls();
}

protected override void CreateChildControls()


{
MyTxt = new TextBox();
RadAjax for ASP.NET AJAX 41

MyLbl = new Label();

//set IDs of instantiated controls!


MyLbl.ID = "Lbl_" + m_UniqueId;
MyTxt.ID = "Txt_" + m_UniqueId;

MyLbl.Text = "LabelText";

//add the controls into controls collection!


this.Controls.Add(MyTxt);
this.Controls.Add(MyLbl);

//Manually add AJAX request triggered on onBlur client event of the text box
MyTxt.Attributes.Add("onBlur", m_radAm.GetAjaxEventReference(MyTxt.ClientID));

//Add the ajax setting - this should be done after controls are added into controls collection
m_radAm.AjaxSettings.AddAjaxSetting(m_radAm, MyLbl);
}

public TextBox controTB


{
get {
return MyTxt;
}
}

public Label controLbl


{
get
{
return MyLbl;
}
}

protected override void Render(HtmlTextWriter output)


{
MyTxt.RenderControl(output);
MyLbl.RenderControl(output);

}
}

5.3  Troubleshooting
5.3.1 Ajaxifying controls wrapped in RadAjaxPanel and added to
AJAX Manager settings

We highly recommend avoid working with the RadAjaxManager & RadAjaxPanel controls at the same
time. Use the controls depending on your exact scenario as recommended here ('Manager vs. Panel'
in the on-line documentation).

If one and the same control is placed in RadAjaxPanel as well as included in RadAjaxManager settings as
ajaxified control (i.e. it is ajaxified by both the panel and manager), the corresponding manager's setting will
not work. In this case the AJAX Panel ajaxifies that control instead of the manager. RadAjaxPanel is designed
to update only its content, therefore you can not use the manager to update other controls outside of the panel
from control ajaxified by the manager and inside the RadAjaxPanel.
The code snippet below will not work as expected (the button won't update the label):
RadAjax for ASP.NET AJAX 42

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


<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="RadAjaxPanel" />
<telerik:AjaxUpdatedControl ControlID="Label1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>

<telerik:RadAjaxPanel ID="RadAjaxPanel" runat="server">


<asp:Button ID="Button1" runat="server" Text="Update Button" />
<asp:TextBox ID="TextBox1" runat="server" Text="Update me" ></asp:TextBox>
</telerik:RadAjaxPanel>

<asp:Label ID="Label1" runat="server">Me too</asp:Label>

The RadAjaxPanel functionality can be simulated completely by the manager - simply replace the AJAX Panel
with an ASP:Panel. The modified version of the above code will perform the same task as if you use
RadAjaxPanel instead of manager:

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


<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Panel1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Panel1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>

Moreover, you are free from the limitation to update controls only within the boundaries of the ajax panel.
Here is the entire solution of the problematic settings defined in the begging of this article:

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


<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Panel1" />
<telerik:AjaxUpdatedControl ControlID="Label1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>

<asp:Panel ID="Panel" runat="server">


<asp:Button ID="Button1" runat="server" Text="Update Button" />
<asp:TextBox ID="TextBox1" runat="server" Text="Update me" ></asp:TextBox>
</asp:Panel>

<asp:Label ID="Label1" runat="server">Me too</asp:Label>

Keep in mind that you can switch the ajaxified "Button1" with "Panel1" if necessary. However, the refresh of
RadAjax for ASP.NET AJAX 43

the controls embed in the panel can take a bit longer time in comparison with hitting an ajaxified button.

5.3.2 Ajaxified control still postbacks


Symptom: You have added AjaxSetting for a control to be ajaxified, but it still makes regular postbacks.
You may have:

5.3.2.1 1) AjaxSettings defined in ASPX


Please, verify whether the control ID matches completely in correspondent AjaxSetting. You may check
whether AJAX Manager designer shows your control as ajaxified, which will ensure that the manager will find
and ajaxify this control at runtime.

5.3.2.2 2) AjaxSettings defined in the code-behind.


Check if you are adding your AjaxSettings on any control's event-handler? AjaxSettings are not preserved
in the ViewState so you have to add them on each PageLoad. In cases like this you may find your "ajaxified"
control making postback on the first try.

5.3.3 AJAX Manager Designer does not locate all controls


RadAjaxManager designer is not able to locate controls on the page in some specific scenarios, but still
those controls can be ajaxified and updated by AJAX Manager:
1) Controls are placed in cells of ASP:Table.
Those table cells need to have an ID set as well as runat="server" included and the designer will locate all the
controls within the table. Here is an example:

<asp:Table ID="Table1" runat="server">


<asp:TableRow runat="server" ID="rol_1">
<asp:TableCell runat="server" ID="cell_11">
<asp:Panel ID="Panel1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Panel>
</asp:TableCell>
<asp:TableCell runat="server" ID="cell_12"></asp:TableCell>
<asp:TableCell runat="server" ID="cell_13"></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="row_2">
<asp:TableCell runat="server" ID="cell_21">
<div runat="server" id="div1">
<asp:CheckBox ID="CheckBox1" runat="server" />
</div>
</asp:TableCell>
<asp:TableCell runat="server" ID="cell_22"></asp:TableCell>
<asp:TableCell runat="server" ID="cell_23"></asp:TableCell>
</asp:TableRow>
</asp:Table>

Then the button, check box and text box could be located by designer and the following AJAX settings could be
added:

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


<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="TextBox1" />
RadAjax for ASP.NET AJAX 44

</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="CheckBox1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="TextBox1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>

2) Control is nested in a template of a composite control.


Those templates may "hide" wrapped controls from the AJAX Manager Designer. We plan to remove this
limitation, but meanwhile we recommend adding AJAX settings programmatically (set-ajaxsettings-
programmatically.html) in such scenarios, which approach together with FindControl method usage,
provides AJAX Manager with the ability to ajaxify and update controls at all "levels" of the application. For
example if the control you want to update is located within RadDockableObject (see RadDock
(http://www.telerik.com/RadDock) web control), it could be found at runtime using
RadDockableObject.FindControl("<controlID>") and then set it as updated control.
See the AJAX RadDock online demo
(http://www.telerik.com/demos/aspnet/Controls/Examples/Integration/Ajax/Dock/DefaultCS.aspx)
where this approach is followed.

3) Controls are placed in a WebUserControl.


The above (from 2)) is valid here as well. You could use the same approach and add AJAX settings
dynamically.
See also how to ajaxify user controls (Section 5.2.2).

4) Controls are placed in a different content of MasterPage scenario.


Again the same approach could be followed as the controls are hidden from the designer when placed in
content place holder.
See also how to deal with AJAX in MasterPage scenario (Section 5.2.3).

5.3.4 Layout problem: Updated controls on new line


You may notice controls rendered on new line when added into the AJAX Manager settings. This is because
RadAjaxManager dynamically inserts UpdatePanels around the updated controls. The UpdatePanel default
render mode is Block, which causes the layout change.
Since the official release of RadControls for ASP.NET AJAX in April 2008, RadAjaxManager exposes new
property - UpdatePanelRenderMode. One can use it to control the render mode of the dynamically
inserted UpdatePanels:

RadAjaxManager UpdatePanelRenderMode
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"
UpdatePanelsRenderMode="Inline">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadGrid1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="RadGrid1" />
<telerik:AjaxUpdatedControl ControlID="Label1" />
<telerik:AjaxUpdatedControl ControlID="Label2" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
RadAjax for ASP.NET AJAX 45

</telerik:RadAjaxManager>

The Inline render mode will ensure the layout will not change when the AJAX settings are added. Otherwise,
RadAjaxManager will persist the default UpdatePanel render mode.

5.3.5 SharePoint WebPart: Dynamically added manager is


missing in Page.Controls
RadAjax controls for ASP.NET AJAX support SharePoint and can be integrated with WebParts.
There is a minor detail to be taken into account when adding RadAjaxManager dynamically into a
WebPart, though. The control should be added both to Page.Form.Controls collection as well as to
Page.Items collection. Otherwise, the code accessing the manager in order to add the necessary AJAX settings
for example, would return null:

C#: Accessing Script and AJAX Manager controls


ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
RadAjaxManager ajaxManager = RadAjaxManager.GetCurrent(this.Page);
myManager.AjaxSettings.AddAjaxSetting(Button1, Label1); //may throw null
reference exception

We recommend using WebPart OnInit event to add the AJAX Manager dynamically:
C#: Adding AJAX Manager in OnInit WebPart event
myAjaxManager = new RadAjaxManager();
myAjaxManager.ID = "RadAjaxManager1";
this.Page.Items.Add(myAjaxManager.GetType(), myAjaxManager);
this.Page.Form.Controls.Add(myAjaxManager);
VB.NET: Adding AJAX Manager in OnInit WebPart event
myAjaxManager = New RadAjaxManager
myAjaxManager.ID = "RadAjaxManager1"
Me.Page.Items.Add(myAjaxManager.GetType, myAjaxManager)
Me.Page.Form.Controls.Add(myAjaxManager)

as well as adding the necessary AJAX settings (Section 5.2.1) into the Page_PreRender event.
RadAjax for ASP.NET AJAX 46

6  RadAjaxPanel Control
6.1  AJAX Panel
AJAX Panel is one of the two major controls of the Telerik RadAjax suite. The other one is AJAX Manager
(Section 5.1). The AJAX Panel control provides the easiest way to AJAX-enable ASP.NET web control(s).
To do this you simply need to place the controls that you want ajaxified into AJAX Panel and Telerik
RadAjax takes care of the rest. Best of all this happens transparently to the framework and the controls that are
being ajaxified.
The main features of AJAX Panel are:
 Ajaxifies all controls inside that normally work with postbacks.
 Defines visually and codeless (in Visual Studio design-time) which elements should be updated via AJAX
requests. All elements wrapped in the panel will be updated via AJAX
 No need to modify your application logic
 Allows you to update a number of page elements at once
 No need to write any JavaScript or invoke AJAX requests manually

6.1.1 AJAX Panel Usage


All you need to do is to drag the control you want to make callbacks into the AJAX Panel. Then it will start
performing callbacks instead of postbacks. On the image below you see a typical usage scenario. A standard
ASP.NET control (calendar in this case) is placed in an AJAX Panel. On the web form there is also a
Loading Panel (Section 8.1) that will be shown in the place of the AJAX Panel during the AJAX request.

Note that the whole AJAX Panel (with ALL controls inside) is updated when one of the controls
makes an AJAX request. Thus if you put the whole page into a AJAX Panel, this may cause reduced
performance, as all controls within the panel will be updated, not just the AJAX initiator.
Placing the whole page into a AJAX Panel is usable when you have relatively small number of controls
on the page.
RadAjax for ASP.NET AJAX 47

Out-of-Panel Update
The following approach is not recommended as RadAjaxManager can handle any complex scenarios. You
can just use ASP:Panel controls for example and link them via manager's settings. One and the same panel
may be set as AJAX Initiator and updated control, which will cause the same as RadAjaxPanel functionality.
There are cases when you may want to update the information inside the panel by triggering a callback
externally from other control on the page. You need to make a call to the <%RadAjaxPanel1.ClientID%
>.ajaxRequest() method (passing the necessary information as parameters to it) and then override the
RaisePostBackEvent method to apply the changes. Here is a sample implementation, which changes the
background color of the panel:

[ASPX/ASCX]
<asp:ScriptManager ID="ScriptManager" runat="server"/>
<telerik:RadAjaxPanel id="RadAjaxPanel1" runat="server"
EnableAJAX= "True">
</telerik:RadAjaxPanel>
<br />
<input type=button value="Change color" onclick='<%=RadAjaxPanel1.ClientID%>.ajaxRequestWithTarg
And in the code-behind:
[VB.NET]
Protected Overrides Sub RaisePostBackEvent(ByVal source As IPostBackEventHandler, ByVal eventArgument
MyBase.RaisePostBackEvent(source, eventArgument)
Select Case eventArgument
Case "ChangeColor"
RadAjaxPanel1.BackColor = Color.Maroon
End Select
End Sub
[C#]
protected override void RaisePostBackEvent(IPostBackEventHandler source, String eventArgument)
{
base.RaisePostBackEvent(source, eventArgument);
switch(eventArgument)
{
case "ChangeColor":
RadAjaxPanel1.BackColor = Color.Maroon;

break;
}
}

6.1.2 ajaxRequestWithTarget() reference


You can make any external control to force AJAX Panel perform an AJAX request by calling this client-side
function. When using this function the event target defaults to the RadAjaxPanel instance.

You can construct the javascript function calls manually or alternatively use the server-side method
GetAjaxEventReference and have Telerik RadAjax generate the necessary code for you.

__doPostBack(eventTarget, eventArgument)
or
$find("<%=RadAjaxPanel1.ClientID%>").ajaxRequestWithTarget(eventTarget,
eventArgument)
eventTarget The control which should raise postback event. You should use the control's UniqueID.
eventArgument This is optional argument for the event
RadAjax for ASP.NET AJAX 48

6.1.3 ajaxRequest() reference:

$find("<%=RadAjaxPanel1.ClientID%>").ajaxRequest(arguments)
arguments The parameters, which the control had used when it raised the request

When either of these functions is is called on the client it can be handled in the AjaxRequest event handler
on the server.

6.2  How-To
6.2.1 Achieve interaction between AJAX Panels
First of all, note that RadAjaxPanel control is designed to update only its content controls so it is
always recommended using RadAjaxManager when an update to external controls is needed.
However, you can achieve interaction between panels without the use of RadAjaxManager. The example
below uses ResponseScripts property, together with client-side AjaxRequest (Section 9.1) function.
Note the use of Page_PreRender event as well as the property persisted in ViewState.

[ASPX/ASCX]
<asp:ScriptManager ID="ScriptManager" runat="server" />
<h3>Panel1</h3>
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
<asp:Button ID="btnIncrease" OnClick="btnIncrease_Click" Text="Increase" runat="serve
</asp:Button>
<asp:Label ID="Label1" runat="server">0</asp:Label>
<asp:TextBox ID="TextBox1" Text="0" runat="server"></asp:TextBox>
</telerik:RadAjaxPanel>
<h3>Panel2</h3>
<telerik:RadAjaxPanel ID="RadAjaxPanel2" runat="server">
<asp:Button ID="btnDecrease" OnClick="btnDecrease_Click" Text="Decrease" runat="serve
</asp:Button>
<asp:Label ID="Label2" runat="server">0</asp:Label>
<asp:TextBox ID="TextBox2" Text="0" runat="server"></asp:TextBox>
</telerik:RadAjaxPanel>
And in the code-behind (C#):

protected void Page_PreRender(object sender, EventArgs e)


{
if (RadAjaxPanel1.IsAjaxRequest || RadAjaxPanel2.IsAjaxRequest)
{
TextBox1.Text = Label1.Text = TextBox2.Text = Label2.Text = Count.ToString();
}
}
public int Count
{
get
{
return this.ViewState["Count"] == null ? 0 : (int)this.ViewState["Count"];
}
set
{
this.ViewState["Count"] = value;
}
}
protected void btnIncrease_Click(object sender, System.EventArgs e)
{
Count++;
RadAjaxPanel1.ResponseScripts.Add(String.Format("$find('{0}').AjaxRequest();", RadAjaxPanel2.
}
RadAjax for ASP.NET AJAX 49

protected void btnDecrease_Click(object sender, System.EventArgs e)


{
Count--;
RadAjaxPanel2.ResponseScripts.Add(String.Format("$find('{0}').AjaxRequest();", RadAjaxPanel1.
}
And VB:

Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreRender


If RadAjaxPanel1.IsAjaxRequest Or RadAjaxPanel2.IsAjaxRequest Then
Dim countValue As String = Count.ToString()
TextBox1.Text = countValue
Label1.Text = countValue
TextBox2.Text = countValue
Label2.Text = countValue
End If
End Sub 'Page_PreRender

Public Property Count() As Integer


Get
If Me.ViewState("Count") Is Nothing Then
Return 0
Else
Return CInt(Me.ViewState("Count"))
End If
End Get
Set(ByVal value As Integer)
Me.ViewState("Count") = value
End Set
End Property

Protected Sub btnIncrease_Click(ByVal sender As Object, ByVal e As System.EventArgs)


Count += 1
RadAjaxPanel1.ResponseScripts.Add(String.Format("$find('{0}').ajaxRequest();", RadAjaxPanel2.
End Sub 'btnIncrease_Click

Protected Sub btnDecrease_Click(ByVal sender As Object, ByVal e As System.EventArgs)


Count -= 1
RadAjaxPanel2.ResponseScripts.Add(String.Format("$find('{0}').ajaxRequest();", RadAjaxPanel1.
End Sub 'btnDecrease_Click

6.2.2 Scroll to top after AJAX


By default RadAjaxPanel maintains the focus of ajaxified control when the response ends. For instance, if you
have a button at the bottom of the page embedded in an AJAX Panel, the button will still be focused when the
update finishes.

However, with a longer page you may need to scroll the page to the top after AJAX (where the updated
controls might be placed).
The following JavaScript function does the trick:

<script type="text/javascript">
function scrollTop()
{
window.document.body.scrollTop = 0;
window.document.documentElement.scrollTop = 0;
}
</script>
RadAjax for ASP.NET AJAX 50

This function has to be added to the ResponseScripts collection of the RadAjaxPanel control in order to be
executed after an AJAX call. Here is a sample code-snippet:

[C#]

private void Page_Load(object sender, System.EventArgs e)


{
RadAjaxPanel1.ResponseScripts.Add("scrollTop();");
}

private void cmd1_Click(object sender, System.EventArgs e)


{
lbl1.Text = System.DateTime.Now.ToString;
//set no active element
RadAjaxPanel1.ActiveElementID = null;
}

[VB]

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.L


RadAjaxPanel1.ResponseScripts.Add("scrollTop();")
End Sub

Private Sub cmd1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmd1.Click


lbl1.Text = Date.Now.ToString
//set no active element
RadAjaxPanel1.ActiveElementID = Nothing
End Sub

The RadAjaxManager control does not maintain focus on active controls after an asynchronous request. If you
need to focus a specific control, manager's FocusControl method can be used. Below is a link to an online
demo demonstrating this aspect of the ajax manager server side API:
http://www.telerik.com/demos/aspnet/prometheus/Ajax/Examples/Common/SettingFocus/DefaultCS.as
RadAjax for ASP.NET AJAX 51

7  AJAX Manager Proxy


7.1  AJAX Manager Proxy
RadAjax no longer allows more than one RadAjaxManager on the page. Instead, in a complex scenario like
WebUserControls (Section 5.2.2) or Master/ContentPages (Section 5.2.3), one should place
RadAjaxManager instance on the main/master page and add a proxy control to the user control/content page.
RadAjaxManagerProxy copies the exact same RadAjaxManager designer configuration (Section 5.1)
so that one can set all the necessary AJAX settings within the WebUserControl/ContentPage entirely through
the designer.

<telerik:RadAjaxManagerProxy ID="AjaxManagerProxy1" runat="server">


<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="DropDownList1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="DetailsView1" />
<telerik:AjaxUpdatedControl ControlID="GridView1" />
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="GridView1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="GridView1" />
<telerik:AjaxUpdatedControl ControlID="DetailsView1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManagerProxy>

The purpose of the new control is to ease the design-time configuration only. The Proxy does not provide
client-side functionality as the Manager does. There is no client-side object (Section 9.3) as well as
functions like ajaxRequest/ajaxRequestWithTarget (Section 9.1) and client-side events (Section
9.2). Instead, one can get the Manager instance through the GetCurrent static method similar to the
ASP:ScriptManager control and call the master manager client-side methods if necessary.

Accessing master manager client-side from user control


<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function myUserControlClickHandler()
{
$find("<%= RadAjaxManager.GetCurrent(Page).ClientID %
>").ajaxRequest("content");
}
</script>
</telerik:RadCodeBlock>

When a server-side code block will be used one should wrap the entire script in a RadCodeBlock.

Should one need to add AJAX settings programmatically (Section 5.2.1), it is recommended to get
the master manager instance and call its methods/properties as well. The same GetCurrent method
could be used to access the AJAX Manager placed in the Master/Main page from a Content
page/WebUserControl.
RadAjax for ASP.NET AJAX 52
RadAjax for ASP.NET AJAX 53

8  RadAjaxLoadingPanel Control
8.1  AJAX Loading Panel
Telerik RadAjax has a support for templates that will be shown as a progress indication when a callback
request is performed, i.e. when the page is loading silently. This will improve the overall feeling of the page as
there will be no sudden changes and unnecessary flickering. There are some sample loading panels below:

8.1.1 Position
In order to have a LoadingPanel, you need to drag it to your web form from the toolbox just like any control.
Then you can set a control to use a LoadingPanel using the design-time. The IsSticky property of the
LoadingPanel defines where the panel will appear. By default, when IsSticky is false, the LoadingPanel
will appear over the updated control. If you set IsSticky to true, the panel will appear where you have set it in
the WebForm.

In case you have many controls added to the AjaxSettings and want to use IsSticky="true", then you need
to set absolute positioning for the LoadingPanel control i.e:
<telerik:RadAjaxLoadingPanel ID="LoadingPanel1" IsSticky="true" runat="server" Height="75px"
Width="75px" style="position:absolute;">
<asp:Image ID="Image1" runat="server" AlternateText="Loading..."
ImageUrl="~/RadControls/Ajax/Skins/Default/Loading.gif" />
</telerik:RadAjaxLoadingPanel>

You can use a single LoadingPanel for many controls. It will show on the place of each control that was set to
use it, IsSticky was set to true.
You can modify the LoadingPanel control as you would do with a normal template. The example below
shows how to set an Image and a Label inside the LoadingPanel.

[ASPX]
<telerik:RadAjaxLoadingPanel
id="LoadingPanel1"
runat="server"
Width="256px"
Height="64px">
<asp:Label id="Label2" runat="server" ForeColor="Red">Loading... </asp:Label>
<asp:Image id="Image1" runat="server" Width="224px" Height="48px" ImageUrl="Loading.gif"></asp:Imag
</telerik:RadAjaxLoadingPanel>

8.1.2 Timing
There are cases when you update a small amount of data. In this scenario the AJAX request executes very fast
and there is not enough time to show the Loading Panel. You see a brief flickering instead, which may seem
annoying and may confuse the site visitor. For this purpose LoadingPanel provides two properties:
InitialDelayTime and MinDisplayTime.
The InitialDelayTime property specifies the delay in milliseconds, after which the LoadingPanel will be
shown. If the request returns before this time, the LoadingPanel will not be shown.
This, however does not solve the scenario, when the request returns shortly after the initial delay time has
passed. The page has just shown the Loading Panel and has to hide it again. The result will be even more
annoying flicker. That's why there is another property for the LoadingPanel: MinDisplayTime. It specifies
the minimum time in milliseconds that the Loading Panel will last. The control will not be shown before this
period has passed even if the request returns. This will ensure more smoother interface for your page.
RadAjax for ASP.NET AJAX 54

8.1.3 Transparency
The loading panel does not "replace" the updated control by default. Instead, it is shown "over" the
control. The Transparency property value should be set in percentage (values 0-100). The default value of
the Transparency property is 0, which means the loading panel is absolutely visible.
See the online demo and check how changing the transparency value changes loading panel appearance.

8.1.4 Explicitly show and hide the loading panel


Loading Panel's Show and Hide methods can be explicitly called on the client. This allows you to update
controls according to some condition and display a loading panel over the control that will be updated (Show
the panel in OnRequestStart (Section 9.5), hide it in OnResponseEnd (Section 9.6)). Review this
topic (Section 8.2.1) for more info.

8.2  How-To
8.2.1 Show and hide loading panel explicitly
To display the loading panel over an element, just call the Show method client-side. This allows you
to conditionaly display loading panel over updated control (Show the panel in OnRequestStart (Section
9.5), hide it in onResponseEnd (Section 9.6)):

JavaScript:

<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">


<script type="text/javascript">
var currentLoadingPanel = null;
var currentUpdatedControl = null;
function RequestStart(sender, args)
{
currentLoadingPanel = $find("RadAjaxLoadingPanel1");

if (args.get_eventTarget() == "Button1")
{
currentUpdatedControl = "Panel1";
}
else
{
currentUpdatedControl = "Panel2";
}
//show the loading panel over the updated control
currentLoadingPanel.show(currentUpdatedControl);
}
function ResponseEnd()
{
//hide the loading panel and clean up the global variables
if (currentLoadingPanel != null)
currentLoadingPanel.hide(currentUpdatedControl);
currentUpdatedControl = null;
currentLoadingPanel = null;
}
</script>
</telerik:RadCodeBlock>
ASPX:

Manager/LoadingPanel Markup

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


RadAjax for ASP.NET AJAX 55

<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">


<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Panel1"
LoadingPanelID="LoadingPanel1" />
<telerik:AjaxUpdatedControl ControlID="Panel2"
LoadingPanelID="LoadingPanel1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
<ClientEvents OnRequestStart="RequestStart"
OnResponseEnd="ResponseEnd" />
</telerik:RadAjaxManager>
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server">
<img alt="Loading..." src='<%= RadAjaxLoadingPanel.GetWebResourceUrl
(Page, "Telerik.Web.UI.Skins.Default.Ajax.loading.gif") %>' style="border:0;" />
</telerik:RadAjaxLoadingPanel>
<asp:Button ID="Button1" runat="server" Text="Postback"
OnClick="Button1_Click" />
<asp:Panel ID="Panel1" runat="server" Width="200px">
Panel 1
</asp:Panel>
<br />
<br />
<br />
<br />
<asp:Panel ID="Panel2" runat="server" Width="200px">
Panel 2
</asp:Panel>

When you use this approach for RadControls, you need to invoke the currentLoadingPanel.hide()
method with a slight change due to the rendering of the RadControls. The code that shows the loading
panels tries to append "_wrapper" at the end of the updated controls, because all of the RadControls'
html wrapper elements end in this suffix. However, the code for hiding the loading panel will not look for
the wrapper suffix, which will cause a javascript error. To use the above script for RadControls please
apply the following change to the hide() method:
currentLoadingPanel.hide(currentUpdatedControl+ "_wrapper" );

8.2.2 Show RadAjaxLoadingPanel on initial page load


Although RadAjaxLoadingPanel is designed to be shown on AJAX updates, someone would like to show it
on initial page load as well. It is not supported out of the box, however it is easy achievable using some
additional code.
The focus on the following example is the window.onload function, which initiates an AJAX request from
the client. To be more functional, we have added an update of an ASP:Panel to this example. Thus, we need an
AJAX Manager setting, where RadAjaxManager updates the panel (shows an initially invisible inner panel
actually).

JavaScript:

<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">


<script type="text/javascript">
window.onload = function()
{
setTimeout( function(){
$find("<%= RadAjaxManager1.ClientID %>").ajaxRequest("InitialPageLoad");
}, 200);
RadAjax for ASP.NET AJAX 56

}
</script>
</telerik:RadCodeBlock>

ASPX:

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


<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxReques
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Panel1" LoadingPanelID="RadAjaxLoadingPanel1"
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
<asp:Panel ID="Panel1" runat="server">
<asp:Panel ID="Panel2" Visible="false" runat="server">
My content:
</asp:Panel>
</asp:Panel>
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Height="75px" Width="75px" Tran
<img alt="Loading..." src='<%= RadAjaxLoadingPanel.GetWebResourceUrl(Page, "Telerik.Web.UI.Skins.
</telerik:RadAjaxLoadingPanel>

[C#]
protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.WebC.UI.AjaxRequestEventArgs e)
{
if (e.Argument == "InitialPageLoad")
{
//simulate longer page load
System.Threading.Thread.Sleep(2000);
Panel2.Visible = true;
}
}

[VB.NET]
Protected Sub RadAjaxManager1_AjaxRequest(ByVal sender As Object, ByVal e As AjaxRequestEventArgs
If e.Argument = "InitialPageLoad" Then
'simulate longer page load
System.Threading.Thread.Sleep(2000)
Panel2.Visible = True
End If
End Sub

8.2.3 Show the loading panel next to AJAX initiator


Sometimes people may want to show the loading panel on a specific position, like right next to the AJAX
initiator for example. When you have a complex control, e.g. tabstrip, it could be better to show the loading
over the clicked tab (say the tabstrip is updated itself via AJAX) instead of showing it on one and the same
place.
In order to achieve that you can use a Sticky loading panel (set IsSticky to "true") and set the loading panel
position at OnRequestStart event, using the event arguments' EventTargetElement attributes. Below is a
sample code you can use and modify according to your exact needs. There are some standard controls (for
simplicity) which are ajaxified and update a label control in this example.
There is just one tricky thing here (the first line from the following RequestStart function) - we clear the
RadAjax for ASP.NET AJAX 57

displayed loading panels cache, otherwise the first loading panel position will be used on each subsequent
request. Then we change left and top attributes of loading panel element style according to the offset of the
event target in this case.

<script type="text/javascript">
function RequestStart(sender, eventArgs)
{
var divElementStyle = document.getElementById("RadAjaxLoadingPanel1").style;
divElementStyle.position = 'absolute';
//position the loading panel
divElementStyle.left = eventArgs.get_eventTargetElement().offsetLeft + "px";
divElementStyle.top = eventArgs.get_eventTargetElement().offsetTop + "px";
}
</script>

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


<telerik:radajaxmanager id="RadAjaxManager1" runat="server">
<ClientEvents OnRequestStart="RequestStart"></ClientEvents>
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Label1" LoadingPanelID="RadAjaxLoading
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="Button2">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Label1" LoadingPanelID="RadAjaxLoading
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="CheckBox1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Label1" LoadingPanelID="RadAjaxLoading
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:radajaxmanager>
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" MinDisplayTime="1000">
<img alt="Loading..." src='<%= RadAjaxLoadingPanel.GetWebResourceUrl(Page, "Telerik.Web.U
</telerik:RadAjaxLoadingPanel>
<asp:Button ID="Button1" runat="server" Text="Button" width="100px"/>
<asp:Label ID="Label1" runat="server" Text="Label" style="z-index: 103; left: 137px; position
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" Text="check box" />
<asp:Button ID="Button2" runat="server" Text="Button2" width="100px"/>

On button and checkbox click events we just update the label server-side.

8.2.4 Center LoadingPanel on the Screen


The code below centers the loading panel on the screen. Note the use of absolute positioning along with Sticky
mode of RadAjaxLoadingPanel control.

<script type="text/javascript">
function centerUpdatePanel()
{
centerElementOnScreen(document.getElementById("LoadingPanel1"));
}

function centerElementOnScreen(element)
{
RadAjax for ASP.NET AJAX 58

var scrollTop = document.body.scrollTop;


var scrollLeft = document.body.scrollLeft;

var viewPortHeight = document.body.clientHeight;


var viewPortWidth = document.body.clientWidth;

if (document.compatMode == "CSS1Compat")
{
viewPortHeight = document.documentElement.clientHeight;
viewPortWidth = document.documentElement.clientWidth;

scrollTop = document.documentElement.scrollTop;
scrollLeft = document.documentElement.scrollLeft;
}

var topOffset = Math.ceil(viewPortHeight/2 - element.offsetHeight/2);


var leftOffset = Math.ceil(viewPortWidth/2 - element.offsetWidth/2);

var top = scrollTop + topOffset - 40;


var left = scrollLeft + leftOffset - 70;

element.style.position = "absolute";
element.style.top = top + "px";
element.style.left = left + "px";
}
</script>

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

<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" ClientEvents-OnRequestStart="centerUpdate

<telerik:RadAjaxLoadingPanel IsSticky="true" ID="LoadingPanel1" runat="Server">


<img alt="Loading..." src='<%= RadAjaxLoadingPanel.GetWebResourceUrl(Page, "Telerik.Web.UI.Skins.
</telerik:RadAjaxLoadingPanel>

A working sample with RadAjaxPanel from regular RadControls suite can be found at this
(http://www.telerik.com/community/forums/thread/b311D-tctab.aspx) forum thread.
RadAjax for ASP.NET AJAX 59

9  Client-Side
9.1  Client-Side API
At client-side you can execute your own JavaScript functions at certain stages of the AJAX request.
Additionally you can use a generic JavaScript function to make explicit AJAX requests to the server from the
client.

You can construct the javascript function calls manually or alternatively use the server-side method
GetAjaxEventReference and have Telerik RadAjax generate the necessary code for you.

Client-side API

The new RadAjax for ASP.NET AJAX requires enclosing the server code blocks inside RadCodeBlock
control. See Changes and backwards compatibility (Section 4.3) article as well as
RadCodeBlock description (Section 15) for more info.

9.1.1
ajaxRequest(arguments)
The ajaxRequest(arguments) function, is used to initiate a generic AJAX request. When using this function
the event target defaults to the RadAjaxPanel or RadAjaxManager instance.

$find("<%=AjaxManager1.ClientID%>").ajaxRequest(arguments)
arguments The parameters, which the control had used when it raised the request

9.1.2 AjaxRequest event


When it is called on the client it can be handled in the ajaxRequest event handler on the server:

[JavaScript]
<telerik:RadCodeBlock ID="cb1" runat="server">
function InitiateAjaxRequest(arguments)
{
var ajaxManager = $find("<%= RadAjaxManager1.ClientID %>");
ajaxManager.ajaxRequest(arguments);
}
</telerik:RadCodeBlock>

And in the code-behind:

[C#]
private void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
//code to handle the generic AJAX request
}
[VB.NET]
Private Sub RadAjaxManager1_AjaxRequest(ByVal sender As Object, ByVal e As AjaxRequestEventArgs)
'code to handle the generic AJAX request
End Sub

When an AJAX request is triggered using AjaxRequest function from the client, the AJAX Manager itself
RadAjax for ASP.NET AJAX 60

should be set as the AJAX initiator updating the corresponding control like this:
[ASPX]
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<telerik:RadAjaxManager id="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxReques
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="TextBox1"></telerik:AjaxUpdatedControl>
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>

9.1.3 ajaxRequestWithTarget(eventTarget, eventArgument)


The ajaxRequestWithTarget(eventTarget, eventArgument) function can be called to simulate a
postback/AJAX request send by other control (besides AjaxManager or AjaxPanel) with the specified
UniqueID and specified arguments. Its execution can be handled by the correspondent event (i.e.
Button_Click) on the server.

__doPostBack(eventTarget, eventArgument)
or
$find("<%=AjaxPanel1.ClientID%>").ajaxRequestWithTarget(eventTarget, eventArgument)
The control which should raise postback event. You should always use the control's
eventTarget
UniqueID.
eventArgument This is optional argument for the event

Note: ajaxRequestWithTarget is designed as a substitute of the standard __doPostBack function. Thus,


you need to override RaisePostBackEvent
of the page in order to get its argument server-side.

Here is an example how to use AjaxRequestWithTarget:

[ASPX]
<input type="button" onclick="AjaxRequestButton(); return false;" value="AjaxButton">
<asp:Button id="Button1" runat="server" Text="Button" OnClick="Button1_Click"></asp:Button>
<asp:TextBox id="TextBox1" runat="server" Text=""></asp:TextBox>
<asp:ScriptManager ID="ScriptManager" runat="server" />
<telerik:RadAjaxManager id="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1" >
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="TextBox1"></telerik:AjaxUpdatedControl>
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>

[JavaScript]
<telerik:RadCodeBlock ID="cb1" runat="server">
function AjaxRequestButton(arguments)
{
var ajaxManager = $find("<%= RadAjaxManager1.ClientID %>");
ajaxManager.ajaxRequestWithTarget('<%= Button1.UniqueID %>', '');
RadAjax for ASP.NET AJAX 61

}
</telerik:RadCodeBlock>
And in the code-behind:

[C#]
protected void Button1_Click(object sender, System.EventArgs e)
{
TextBox1.Text = DateTime.Now.ToLongTimeString();
}
[VB.NET]
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1
TextBox1.Text = DateTime.Now
End Sub
You can see the working example by following this link:

http://www.telerik.com/demos/aspnet/prometheus/Ajax/Examples/Manager/ClientSideAPI/DefaultCS.a

9.2  Client side Events


Client-Side > Client-Side Events
RadAjaxManager and RadAjaxPanel both descend from RadAjaxControl. RadAjaxControl introduces the
AjaxClientEvents property that contains the following events:
 OnRequestStart (Section 9.5): This event is fired when a request to the server is started.
 OnResponseEnd (Section 9.6): This event is fired when a response from the server is processed.

To use these events, simply write a javascript function that can be called when the event occurs. Then assign
the name of the javascript function as the value of the the corresponding property.
[ASP.NET] Assigning client-side events
<script type="text/javascript">
function requestStart(sender, eventArgs)
{
alert('Request start');
}

function responseEnd(sender, eventArgs)


{
alert('Response complete');
}
</script>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<ClientEvents OnRequestStart="requestStart" OnResponseEnd="responseEnd" />
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl
ControlID="TextBox1"></telerik:AjaxUpdatedControl>
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>

9.3  RadAjaxManager Client Object


The following table lists significant methods of the RadAjaxManager client-side object:
RadAjax for ASP.NET AJAX 62

Return
Name Parameters Description
Type

ajaxRequest (client-side- Initiates a AJAX request that fires the AjaxRequest


string none (ServerSideAjaxRequest.html) event on the
basics.html)
server.
ajaxRequestWithTarget Simulates a postback/AJAX request initiated from a
string, string none
(client-side-basics.html) control with a specified UniqueID.

array of Returns an array of settings where each object has


get_ajaxSettings none
objects properties for the InitControlID and another array of
UpdatedControls.
[JavaScript] get_ajaxSettings
var ajaxManager = $find("<%= RadAjaxManager1.ClientID %>");
var settings = ajaxManager.get_ajaxSettings();
var settingsList = '';
for(setting in settings)
{
var initiatingControl = settings[setting].InitControlID;
var controls = settings[setting].UpdatedControls;
var controlList = '';
for(control in controls)
{
controlList += ' ' + controls[control].ControlID;
}
settingsList += '\nInitiated by: ' + initiatingControl +
'\nUpdated Controls: ' + controlList;
}
alert(settingsList);
get_defaultLoadingPanelIDnone string Returns the DefaultLoadingPanelID.
get_enableAJAX none boolean True if AJAX is enabled.

get_enableHistory none boolean True if browser history is enabled during AJAX


requests.
array of
set_ajaxSettings none Sets the array of objects representing the AjaxSettings.
objects
set_defaultLoadingPanelID string none Sets the DefaultLoadingPanelID
Enables or disable AJAX for the AJAX initiator. Pass
set_enableAJAX boolean none "true" to enable AJAX, "false" to have the subsequent
requests performed as standard postbacks.

set_enableHistory boolean none Allows browser history during AJAX requests. Pass
"true" to allow browser history during AJAX requests.
9.4  RadAjaxPanel Client Object
The following table lists significant methods of the RadAjaxPanel client-side object:
Return
Name Parameters Description
Type

array of Returns an array of settings where each object has


get_ajaxSettings none properties for the InitControlID and another array of
objects
UpdatedControls.
[JavaScript] get_ajaxSettings

var ajaxPanel = $find("<%= RadAjaxPanel1.ClientID %>");


var settings = ajaxPanel.get_ajaxSettings();
var settingsList = '';
RadAjax for ASP.NET AJAX 63

for(setting in settings)
{
var initiatingControl = settings[setting].InitControlID;
var controls = settings[setting].UpdatedControls;
var controlList = '';
for(control in controls)
{
controlList += ' ' + controls[control].ControlID;
}
settingsList += '\nInitiated by: ' + initiatingControl +
'\nUpdated Controls: ' + controlList;
}
alert(settingsList);
get_defaultLoadingPanelIDnone string Returns the DefaultLoadingPanelID.
get_enableAJAX none boolean True if AJAX is enabled.

get_enableHistory none boolean True if browser history is enabled during AJAX


requests.
array of Sets the array of objects representing the
set_ajaxSettings none
objects AjaxSettings.
set_defaultLoadingPanelID string none Sets the DefaultLoadingPanelID
Allows or blocks the request to be executed through
set_enableAJAX boolean none AJAX. Pass True to allow AJAX, False to have the
request fulfilled through a standard postback.

set_enableHistory boolean none Allows browser history during AJAX requests. Pass
True to allow browser history during AJAX requests.

9.5  OnRequestStart
The OnRequestStart client -side event handler is called when a request to the server is started. The event can
be initially triggered by an initiating control configured in RadAjaxManager settings, a control within a
RadPanel or by a client-side AjaxRequest() ({2C24091A-F8C3-4822-8664-958BB0548193}) call. The
event can be canceled.
Two parameters are passed to the event handler with the following methods:
 sender the instance of the client-side RadAjaxManager/RadAjaxPanel object.
 eventArgs has the following methods:
 set_cancel() lets you permit or block the AJAX request from continuing. Calling set_cancel(true)
prevents the request from continuing.
 get_eventTarget(), set_eventTarget() : gets or sets the UniqueID of the element that had raised
the request.
 get_eventArgument() , set_eventArgument(): gets or sets the string passed in the initial AJAX
request.
 get_eventTargetElement(), set_eventTargetElement(): gets or sets the instance of the client-
side object that raised the AJAX request
 get_enableAjax(), set_enableAjax(): gets or sets if an AJAX request is performed.
set_enableAjax(false) causes the request to be performed via standard postback.

The following example uses displays the control that initiated the request.
[ASP.NET] OnRequestStart
<script type="text/javascript">
function requestStart(sender, eventArgs)
RadAjax for ASP.NET AJAX 64

{
alert('Request start initiated by: ' +
eventArgs.get_eventTarget());
}
</script>
<asp:ScriptManager ID="ScriptManager" runat="server" />
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<ClientEvents OnRequestStart="requestStart" />
</telerik:RadAjaxManager

9.6  OnResponseEnd
The OnResponseEnd client -side event handler is called when a request to the server is started. The event
can be initially triggered by an initiating control configured in RadAjaxManager settings, a control within a
RadPanel or by a client-side AjaxRequest() ({2C24091A-F8C3-4822-8664-958BB0548193}) call. The
event can not be canceled.
Two parameters are passed to the event handler with the following methods:
 sender the instance of the client-side RadAjaxManager/RadAjaxPanel object.
 eventArgs has the following methods:
 get_eventTarget(), set_eventTarget() : gets or sets the UniqueID of the element that had raised
the request.
 get_eventArgument() , set_eventArgument(): gets or sets the string passed in the initial AJAX
request.
 get_eventTargetElement(), set_eventTargetElement(): gets or sets the instance of the client-
side object that raised the AJAX request

The following example uses displays the control that initiated the request.
[ASP.NET] OnResponseEnd
<script type="text/javascript">
function responseEnd(sender, eventArgs)
{
alert('Response end initiated by: ' +
eventArgs.get_eventTarget());
}
</script>
<asp:ScriptManager ID="ScriptManager" runat="server" />
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<ClientEvents OnResponseEnd="responseEnd" />
</telerik:RadAjaxManager

9.7  Client-side How-To


9.7.1 Executing custom javascript code after AJAX update
Telerik RadAjax offers the ability to execute custom JavaScript code which comes as a response from the
server thus giving you more flexibility to complete more specific or complex tasks on the client.
The best and most intuitive approach is to use the ResponseScripts property of the RadAjaxPanel or
RadAjaxManager.
Here is a source code example which pops an alert when a Button is clicked:
private void Button1_Click(object sender, System.EventArgs e)
{
AjaxManager1.ResponseScripts.Add(string.Format("alert('Hello from the server! Server time is {
}
RadAjax for ASP.NET AJAX 65

Another approach, however, is to simply add a literal control to the Controls collection of the panel which
contains the necessary script:
string script = "<script type='text/javascript'>alert('hi');</script>";
AjaxPanel1.Controls.Add(new LiteralControl(script));

For cases when you have code blocks in the .aspx you might encounter "Cannot modify controls collection .."
error. In this case, place an asp:PlaceHolder in the AJAX Panel and add the Literal to its Controls
collection instead:
string script = "<script type='text/javascript'>alert('hi');</script>";
PlaceHolder1.Controls.Add(new LiteralControl(script));

You can also check this KB article (http://www.telerik.com/support/knowledge-base/kb-


article.aspx?b454K=tbg&b454T=ceh) out.

9.7.2 Cancel AJAX request


You can cancel an AJAX request in a client-script function simply by returning value false. The client-script
function can be called upon OnRequestStart event.

[JavaScript]
function CheckZipCode()
{
var zipCode = $get('<%=TextBox1.ClientID%>').value;
if (zipCode.length != 5)
{
alert('Please enter a valid 5 digit postal code!');
return false; // cancel the AJAX request
}
else
{
var fiveDigitCheckRE=/^\d{5}$/ //regular expression for checking a 5 digit number
if (zipCode.search(fiveDigitCheckRE) == -1)
{
alert("Only digits are allowed!"); return false; // cancel the AJAX request
}
}
}

9.7.3 Client confirmation and AJAX


One may need to provide a confirmation dialog to the users and initiate an AJAX request if accepted.
Confirmation using standard post backs often looks like this:
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="return confirm('Are you sure?');"

The OnClientClick should be changed a bit to work with AJAX:


<asp:ImageButton ID="ImageButton2" runat="server" OnClientClick="if (!confirm('Are you sure?')) retur
when the button is ajaxified by added the necessary AJAX setting to RadAjaxManager or when the button is
placed within RadAjaxPanel control.

Alternatively, the OnRequestStart client-side event could be used to implement more complex logic. Here is
a sample script:

<script type='text/javascript'>
RadAjax for ASP.NET AJAX 66

function OnRequestStart(ajaxControl, eventArgs)


{
var eventTarget = eventArgs.EventTarget;
if (eventTarget == "<%= ImageButton1.ClientID %>")
{
return confirm('Are you sure?');
}
else
{
return false;
}
}

9.7.4 Pass more than one argument


By default the ajaxRequest and ajaxRequestWithTarget functions accept only one argument. Sometimes
one might need to pass more arguments - this can be achieved by joining the arguments on the client:
[Javascript]
var arg3 = arg1 + "," + arg2;

ajaxManager.ajaxRequest(arg3);

and split them on the server in the AjaxManager_AjaxRequest:

[C#]
private void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
string argument = (e.Argument);
String[] stringArray = argument.Split(",".ToCharArray());
}

[VB.NET]
Protected Sub RadAjaxManager1_AjaxRequest(ByVal sender As Object, ByVal e As AjaxRequestEventArgs) Ha
Dim argument As String = e.Argument
Dim stringArray As [String]() = argument.Split(",".ToCharArray())
End Sub
Online example showing this in action is available here
(http://www.telerik.com/DEMOS/ASPNET/Controls/Examples/Integration/Ajax/TreeView/DefaultCS.asp

9.7.5 Forcing postback
If you want to perform a single postback instead of AJAX request, arguments.EnableAjax should be false:
In the code-behind:

[C#]
if (!RadAjaxManager1.EnableAJAX)
{
RadAjaxManager1.ClientEvents.OnRequestStart = "OnRequestStart";
}
On the client:

[ASPX/ASCX]
<script type="text/javascript">
RadAjax for ASP.NET AJAX 67

function OnRequestStart(sender, args)


{
args.set_enableAjax(false);
}
</script>
This approach is useful only when you want to perform a single postback. If you want to disable ajax because
of unsupported browsers or old versions of supported ones we suggest you to do this on the server:

RadAjaxManager1.EnableAJAX = Page.Request.Browser.SupportsXmlHttp;

9.7.6 Assign different Client-events for different controls


In order to assign different client-events to different ajaxified controls you can use the following approach:

[ASPX]
<asp:ScriptManager ID="ScriptManager" runat="server" />
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"><AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Label1" />
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="DropDownList1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Label1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
<ClientEvents OnRequestStart="Start" OnResponseEnd="End" />
</telerik:RadAjaxManager>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChange
<asp:ListItem>111</asp:ListItem>
<asp:ListItem>222</asp:ListItem>
</asp:DropDownList>
<script type="text/javascript">
function Start(sender, arguments)
{
if (arguments.EventTarget == "<%= Button1.UniqueID %>")
{
alert("StartButton");
}
if (arguments.EventTarget == "<%= DropDownList1.UniqueID %>")
{
alert("StartDropdown");
}
}
function End(sender, arguments)
{
if (arguments.EventTarget == "<%= Button1.UniqueID %>")
{
alert("EndButton");
}
if (arguments.EventTarget == "<%= DropDownList1.UniqueID %>")
{
alert("EndDropdown");
}
}
</script>

This way the DropDownList and the Button will have different client-events although using the same
RadAjaxManager or RadAjaxPanel.

9.7.7 Change mouse cursor on AJAX update


RadAjax for ASP.NET AJAX 68

Changing the mouse cursor on Ajax update could be achieved using the client-side event of Telerik RadAjax
controls. The easiest way is to use the following events script:
function OnRequestStart(sender, args)
{
document.body.style.cursor = "wait";
};

function OnResponseEnd(sender, args)


{
document.body.style.cursor = "default";
};

Here is another solution using additional CSS classes:

<script type="text/javascript">
function RequestStart(sender, args)
{
document.body.className = document.body.className.replace("Normal", "Wait");
}
function ResponseEnd(sender, args)
{
document.body.className = document.body.className.replace("Wait", "Normal");
}
</script>
<style type="text/css">
.Wait
{
}

.Normal
{
}

/* override input cursors with a more specific CSS selector */


.Wait INPUT
{
cursor: wait;
}

.Normal INPUT
{
cursor: default;
}

/* override grid cursors with a more specific CSS selector */


.Wait TABLE
{
cursor: wait;
}

.Normal TABLE
{
cursor: default;
}
</style>
RadAjax for ASP.NET AJAX 69

10  General FAQ and How-to


10.1 Frequently Asked Questions
1. Q: I have a button and a control (RadTreeView for example). The button should update the control with
AJAX. How should I proceed?
A: You should use RadAjaxManager. In the left pane of its designer select the button and in the middle
pane select the treeview. Click OK and run the page.

2. Q: My control is within RadAjaxPanel and I want to update a control in another RadAjaxPanel. Is this
possible?
A: Instead of using two AJAX Panels, consider using a single AJAX Manager.
However if you still want to use the two panels, you should make external call from the AJAX-initiator
control to the AjaxRequest client-side function of the target AJAX Panel. (see AJAX Panel (Section
6.1) topic)

3. Q: I need to load an user control dynamically with AJAX. Is this possible?


A: There is no difference between the standard loading of controls and AJAX loading. Please, carefully
review the Loading User Controls (Section 10.3) topic in order to correctly load user controls
dynamically.

4. Q: I have two controls that interact and update each other. How should I ajaxify them?
A: Depending on your application you can use a single Panel to wrap the two controls or AJAX Manager
in case the controls are non-adjacent.

5. Q: Can I use RadAjaxPanel in another RadAjaxPanel (i.e. nested AJAX Panels)?


A: There should be no problem to use nested AJAX Panels. However we recommend you to revise the
page logic and see if you can achieve the same behavior with RadAjaxManager.

6. Q: I have a client-side code, which is executed on some of the events of a control inside RadAjaxPanel.
How should I proceed?
A: There is nothing special that you need to do in this case - RadAjaxPanel automatically evaluates the
client-side code and does not require you to write additional code.

7. Q: I have a control A, which updates control B, which then updates control C. The control C then updates
control A again. Controls are dependent on each other and should be updated sequentially. What would
you suggest?
A: The answer depends on how the controls are placed on the Page. In case they are neighboring, place
them in AJAX Panel. In case they are non-adjacent, use RadAjaxManager and set the AJAX Relations.

8. Q: I need my controls disabled during AJAX. What should I do?


A: You should hook the Panel/Manager client-side event OnRequestStart and write custom JavaScript
code to achieve your goal. Then you should re-enable it by hooking the OnResponseEnd client-side
event. See this topic (Section 10.8) for details.

10.2 Redirecting to another page


Telerik RadAjax supports two kinds of redirection:
 Response.Redirect() - the standard ASP.NET means of redirection.
 generating JavaScript that sets window.location.href.
RadAjax for ASP.NET AJAX 70

Currently there is a security issue which prevents Response.Redirect with AJAX from working in
Windows Server 2008. IIS 7 simply does not allow to catch the Application events. You should be able to
use RadAjaxManager.Redirect method instead.

Redirecting on the client (JavaScript window.location.href)


RadAjaxManager and RadAjaxPanel also support the Redirect() method, which in essence adds a short
javascript to be evaluated after the AJAX request. The javascript code uses the window.location.href
property to navigate to a new URL.

[C#]
RadAjaxManager1.Redirect("http://www.google.com/");
[VB.NET]
RadAjaxManager1.Redirect("http://www.google.com/")
or

[C#]
RadAjaxPanel1.Redirect("http://www.google.com/");
[VB.NET]
RadAjaxPanel1.Redirect("http://www.google.com/")

Redirect when session times out.


This scenario is automatically handled by the ASP.NET AJAX framework.

10.3 Load user controls


The dynamic loading of user controls follows the same logic as in normal postback application. You can load
custom user controls via AJAX requests by following the steps below:
1. You need to have an appropriate container for it, for example ASP:Panel.
2. Instantiate your user control in Page_Init or Page_Load and always recreate the last loaded User
Control:
[VB.NET]
Dim MyControl As UserControl = Me.LoadControl(controlName)
Me.LoadMyUserControl( Me.CurrentControl, Panel1)

[C#]
UserControl MyControl = (UserControl)LoadControl(controlName);
LoadMyUserControl(CurrentControl, Panel1);
3. Make sure you assign unique ID to the dynamically loaded User Control:

[VB.NET]
Dim userControlID As String = controlName.Split("."c)(0)
MyControl.ID = userControlID.Replace("/", "").Replace("~", "")

[C#]
string userControlID = controlName.Split('.')[0];
MyControl.ID = userControlID.Replace("/", "").Replace("~", "");

5. Place the instance inside the controls collection of the container:


[VB.NET]
parent.Controls.Add(MyControl);
RadAjax for ASP.NET AJAX 71

6. Here is the code from a sample project:

[ASPX]
<asp:Button ID="Button1" runat="server" Text="Load WebUserControl1.ascx" OnClick=
<asp:Button ID="Button2" runat="server" Text="Load WebUserControl2.ascx" OnClick=
<br />
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:ScriptManager ID="ScriptManager" runat="server" />
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="btnLoad1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Panel1" />
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="btnLoad2">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Panel1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>

And in the code-behind:


[VB.NET]
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.
If (Not Me.CurrentControl Is String.Empty) Then
Me.LoadMyUserControl( Me.CurrentControl, Panel1)
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Me.LoadMyUserControl( "~/WebUserControl1.ascx" , Panel1)
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Me.LoadMyUserControl( "~/WebUserControl2.ascx" , Panel1)
End Sub

Private Property CurrentControl() As String


Get
Return IIf(Me.ViewState( "CurrentControl") Is Nothing, String.Empty, Me.ViewState(
End Get
Set(ByVal Value As String)
Me.ViewState("CurrentControl") = Value
End Set
End Property

Private Sub LoadMyUserControl(ByVal controlName As String, ByVal parent As Control)


parent.Controls.Clear()
Dim MyControl As UserControl = Me.LoadControl(controlName)
Dim userControlID As String = controlName.Split("."c)(0)
MyControl.ID = userControlID.Replace("/", "").Replace("~", "")
parent.Controls.Add(MyControl)
Me.CurrentControl = controlName
End Sub

[C#]
protected void Page_Load(object sender, EventArgs e)
{
if (this.CurrentControl != string.Empty)
{
RadAjax for ASP.NET AJAX 72

LoadMyUserControl(CurrentControl, Panel1);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
this.LoadMyUserControl( "~/WebUserControl1.ascx", Panel1);
}
protected void Button2_Click(object sender, EventArgs e)
{
this.LoadMyUserControl( "~/WebUserControl2.ascx", Panel1);
}

private string CurrentControl


{
get
{
return this.ViewState[ "CurrentControl"] == null ? string.Empty : (string)this.ViewSt
}
set
{
this.ViewState[ "CurrentControl"] = value;
}
}

private void LoadMyUserControl( string controlName, Control parent)


{
parent.Controls.Clear();
UserControl MyControl = (UserControl)LoadControl(controlName);
string userControlID = controlName.Split('.')[0];
MyControl.ID = userControlID.Replace("/", "").Replace("~", "");
parent.Controls.Add(MyControl);
this.CurrentControl = controlName;
}

For full code working application you can check this example in RadAjax for ASP.NET AJAX Quick Start
Framework:
http://www.telerik.com/demos/aspnet/prometheus/Ajax/Examples/Common/LoadingUserControls/Defa

10.4 Manually add an AJAX request to a client-side event of an


HTML element
Usually the HTML elements have more client-side events than their server-side counterparts. For example the
asp:TextBox control implements only the TextChanged server-side event while the corresponding HTML
element has a few more: OnMouseOver, OnMouseOut, OnKeyPress, OnKeyUp, OnKeyDown, etc. If
you want to ajaxify one of these client events you have to follow the instructions bellow:
Method 1 not
10.4.1 Method I (add the attribute declaratively)
working!!!
1. Add the OnKeyUp attribute and make it call a custom function:
<asp:TextBox onkeyup="TextBoxCustomAjax('TextBox1');" ID="TextBox1" runat="server" ></asp:TextBox

2. Implement the TextBoxCustomAjax function:


<script type="text/javascript">
function TextBoxCustomAjax(eventArgs)
{
$find("<%=RadAjaxManager1.ClientID %>").ajaxRequest(eventArgs);
}
</script>
3. Implement the AjaxRequest server event of the AjaxManager:
protected void RadAjaxManager1_AjaxRequest( object sender, AjaxRequestEventArgs e)
{
if (e.Argument == TextBox1.ClientID)
RadAjax for ASP.NET AJAX 73

{
Label1.Text = TextBox1.Text;
}
}

4. Set from the designer that the RadAjaxManager1 will update Label1.

TextBox1.Attributes.Add("onkeyup",
10.4.2 Method II (add the attribute from code-behind). RadAjaxManager1.GetAjaxEventReference
(TextBox1.ClientID))
1. Add the OnKeyUp attribute:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add( "onkeyup", RadAjaxManager1.GetAjaxRequestReference(TextBox1.Clie
}
2. Implement the AjaxRequest event of the RadAjaxManager:
protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
if (e.Argument == TextBox1.ClientID)
{
Label1.Text = TextBox1.Text;
}
}
3. Set from the design-time configuration wizard that RadAjaxManager1 will update Label1.

10.5 Exclude controls from ajaxifying


By default the AJAX Panel ajaxifies all controls placed inside. If you want to exclude a control from ajaxifying
you can use one of the following approaches:

1) ScriptManager RegisterPostBackControl method.


An easy solution can be implemented through the ScriptManager's RegisterPostBackControl method. An
example follows:

ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<telerik:RadAjaxPanel runat="server" id="RadAjaxPanel1">
<asp:Button runat="server" id="Button1" text="Ajax" OnClick="Button_Click" />
<asp:Button runat="server" id="Button2" text="Postback"
OnClick="Button_Click" />
<asp:Label ID="Label1" runat="server"></asp:Label>
</telerik:RadAjaxPanel>
C#
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager1.RegisterPostBackControl(Button2);
}
protected void Button_Click(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
RadAjax for ASP.NET AJAX 74

2) Disable AJAX for the current request


Use OnRequestStart client-side event (Section 9.5) handler to determine the AJAX initiator and disable
AJAX for the current request. The event is fired on each request so on the next one the same check will be
performed. A similar implementation is often used in case of exporting from AJAXified Grid:
Export RadGrid content to Excel/Word/CSV/PDF with Ajax enabled
(http://www.telerik.com/community/code-library/submission/b311D-ttcbe.aspx)

3) Add post back function manually


1. Implement the realPostBack function into your aspx/ascx file
2. Add a custom OnClick attribute to the control (Button in this case).

[ASPX]
<telerik:RadCodeBlock id="codeblock1" runat="server">
<script type="text/javascript">
function realPostBack(eventTarget, eventArgument)
{
$find("<%= RadAjaxPanel1.ClientID %>").__doPostBack(eventTarget, eventArgument);
}
</script></telerik:RadCodeBlock>

<asp:Button ID="Button1" runat="server" Text="Button" />


<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ScriptManager ID="ScriptManager" runat="server" />
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server" Text="PostBack"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" Text="Ajax"></asp:LinkButton>
</telerik:RadAjaxPanel>
And in the code-behind (Page_Load event handler):
[C#]
if (!Page.IsPostBack)
{
LinkButton1.Attributes.Add( "onclick", string.Format("realPostBack(\"{0}\", \"\"); return false;"
}
[VB.NET]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
LinkButton1.Attributes.Add( "onclick", String.Format("realPostBack('{0}', ''); return false;"
End If
End Sub
If you do not have a control that registers the __doPostBack function on the page you should add the
following line in the Page_Load as well:
this.Page.ClientScript.GetPostBackEventReference(this, "");

This will come handy when you want a single control to perform post-back for your scenario or you want to
upload files from control in RadAjaxPanel.

Exclude Dynamically Loaded Controls


In case you are loading the user control dynamically, the code if (!Page.IsPostBack) in the example above
in its Page_Load event handler is never executed. You can check for the attached OnClick event instead of
the IsPostBack. For example:

[C#]
RadAjax for ASP.NET AJAX 75

protected void Page_Load(object sender, EventArgs e)


{
bool isOnClickAttached = false;
IEnumerator keys = this.CheckBox1.Attributes.Keys.GetEnumerator();
while(keys.MoveNext())
{
if(keys.Current.Equals("onClick"))
{
isOnClickAttached = true;
break;
}
}
if(!isOnClickAttached)
this.CheckBox1.Attributes.Add( "onClick", string.Format("realPostBack(\"{0}\", \"\"); return
}
[VB.NET]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim isOnClickAttached As Boolean = false
Dim keys As IEnumerator = Me.CheckBox1.Attributes.Keys.GetEnumerator

While keys.MoveNext
If keys.Current.Equals("onClick") Then
isOnClickAttached = true
'TODO: Warning!!! break;If
End If

End While
If Not isOnClickAttached Then
Me.CheckBox1.Attributes.Add( "onClick", String.Format("realPostBack(\""{0}\"", \""\""); return fals
End If
End Sub

10.6 Incompatible controls and updating 3rd party controls with


Telerik RadAjax
Basically you should first check if the control is MS AJAX compatible (MS AJAX is the MS framework for ajax-
enabling controls). If the control works with it, it will most likely work without problems with our AJAX
framework as well. Technical difficulties may occur when updating 3rd party controls which use JavaScript
code on client-side outside of the updating area. As controls are not aware that they are being updated
by AJAX (rather than a postback), they cannot restore their client-side functionality as the HTML element is
being replaced by a new object. Things to check for:
1. The control, which is to be updated via AJAX request should be aware of this fact. This means that it has
to be pre-modified to work with XmlHttpRequests. This should be done by its vendor, so please contact
the control's vendor for help on the issue.
All Telerik RadControls for ASP.NET have been modified and are ready to be used with
Telerik's AJAX controls.

2. Make sure the control renders in one tag. This will ensure its proper update. You can check this by viewing
the page's source. If the control does not render in one tag, you should nest it in a ASP Panel or a DIV tag.

Controls that Are Not Compatible with RadAjaxManager Control


The following ASP.NET controls are not compatible with partial-page updates, and are therefore not supported
as initiating or updated controls:
 TreeView (http://msdn2.microsoft.com/en-us/k5c13faz) and Menu
(http://msdn2.microsoft.com/en-us/07b8w058) controls.
 Web Parts controls. For more information, see ASP.NET Web Parts Controls
RadAjax for ASP.NET AJAX 76

(http://msdn2.microsoft.com/en-us/library/ab78a66e-9feb-4391-b3c3-8c07555e2308).
 FileUpload (http://msdn2.microsoft.com/en-us/ysf0192b) controls when they are used to
upload files as part of an asynchronous postback.
 GridView (http://msdn2.microsoft.com/en-us/4w7ya1ts) and DetailsView
(http://msdn2.microsoft.com/en-us/7z482d0y) controls when their
EnableSortingAndPagingCallbacks property is set to true. The default is false.
 Login (http://msdn2.microsoft.com/en-us/t863ehhh), PasswordRecovery
(http://msdn2.microsoft.com/en-us/t92zy5x0), ChangePassword
(http://msdn2.microsoft.com/en-us/s1xhe282), and CreateUserWizard
(http://msdn2.microsoft.com/en-us/6s8b6814) controls whose contents have not been converted
to editable templates.
 The Substitution (http://msdn2.microsoft.com/en-us/9ze89as6) control.
 Validation controls, which includes the BaseCompareValidator
(http://msdn2.microsoft.com/en-us/z8fh4ax6), BaseValidator
(http://msdn2.microsoft.com/en-us/fczazdzk), CompareValidator
(http://msdn2.microsoft.com/en-us/d7365skb), CustomValidator
(http://msdn2.microsoft.com/en-us/303z9x0x), RangeValidator
(http://msdn2.microsoft.com/en-us/ccs7ftb0), RegularExpressionValidator
(http://msdn2.microsoft.com/en-us/sffh7429), RequiredFieldValidator
(http://msdn2.microsoft.com/en-us/ycxs7t4x), and ValidationSummary
(http://msdn2.microsoft.com/en-us/xd4c894c) control.

Controls that are incompatible with partial-page rendering can still be used on a page without being added to
the AjaxSettings. To make the validators compatible with the RadAjax controls, set the EnableClientScript
(http://msdn2.microsoft.com/en-us/7t054e90) property of the validators to false. This disables the
client script that would ordinarily be used to perform validation in the browser. As a result, during an
asynchronous postback, the validators perform validation on the server. However, because only the content of
the UpdatePanel is refreshed, the validators can provide the kind of immediate feedback that is ordinarily
provided by client script.

10.7 Disable AJAX when client browser does not support it


Telerik RadAjax controls won't work on browsers that do not support XmlHttp requests
(http://en.wikipedia.org/wiki/XMLHttpRequest). You may want to disable AJAX when such a browser
opens your site. This could be easily achieved by setting the EnableAJAX property of used Telerik RadAjax
control to false both on client- and server-side.
The .NET2 framework provides SupportsXmlHttp property and it should be used to check if the browser
supports XmlHttpRequest:

RadAjaxManager1.EnableAJAX = Page.Request.Browser.SupportsXmlHttp;
When this check is made in Page_Load event handler it will make your page work as in standard postback
scenario for those browsers.

Some browsers do support xmlhttp requests and still return false for SupportsXmlHttp. In such cases
you should define Browser definition files - more info is available in the links below.

10.8 Disable controls during AJAX


You may want to disable control during AJAX, so the clients won't be able to use it before response end. This
could easy be achieved using OnRequestStart (Section 9.5) and OnResponseEnd (Section 9.6) client-
side events changing the disabled value.
Here is a complete working code showing the mentioned approach:

<script type="text/javascript">
function RequestStart(sender, args)
{
RadAjax for ASP.NET AJAX 77

args.EventTargetElement.disabled = true;
}
function ResponseEnd(sender, args)
{
args.EventTargetElement.disabled = false;
}
</script>

<asp:Button ID="btnUpdate" runat="server" Text="Update" />


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

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


<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" >
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="btnUpdate">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Label1"/>
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
<ClientEvents OnRequestStart="RequestStart" OnResponseEnd="ResponseEnd" />
</telerik:RadAjaxManager>

Implementing the above will disable any control, which has already start a request until its response ends.

If one wants to disable AJAX until the current response finishes, no matter which control has started the first
request and which is going to make a second one, a global flag may be used as in the following script:

<script type="text/javascript">
var AjaxIsActive = false;

function RequestStart()
{
if (!AjaxIsActive)
{
AjaxIsActive = true;
}
else
{
alert('Wait for ajax to finish');
return false;
}
}

function ResponseEnd()
{
AjaxIsActive = false;
}
</script>

10.9 How to use Css Conditional Comments with Ajax


With the advent of Internet Explorer 7 (IE 7), there is now little choice but to create separate style sheets for
different browsers, at least for a moderately complex visual design or layout. One of the approaches is to use
Conditional Comments. The advantages of that are:
 Only browsers that need (or take advantage) of the style sheets will download them;
 The base style sheets (should) be completely standards based, serving as the foundation (i.e. any
RadAjax for ASP.NET AJAX 78

new/obscure browser has no excuse if it supports CSS);


 No validation issues for browser specific code such as IE’s expressions, or untested CSS 3 rules.

This article explains how to take advantage of the Css conditional comments and still be able to use our ajax
controls.
What the RadAjaxManager does, is look for link or style tags and adds them to the page on ajax request. It
skips the conditional comments and therefore all styles are loaded after ajax request, no matter which browser
or version it is. Unfortunately we have not found a feasible way to check for those and we cannot easily fix this
problem. However we have found two workarounds for the time being which depend on the scenario,
developer and his needs :
 set the EnablePageHeadUpdate property of the ajax control to false - this way it will not update the
head tag. However if you load dynamically controls with ajax, their stylesheets will not be applied in this
case. This is fixable as well - you just need to manually add the stylesheet declarations for the controls on
the page.
 move the conditional comments out of the head tag. This way they will not be updated by the
RadAjaxManager and still applied depending on the browser used. It is even valid xhtml1.1 as the html
comments are skipped by the html validator i.e.:

<body>
<!--[if lte IE 6]>
<link rel="stylesheet" type="text/css" href="ie6.css" />
<![endif]-->
<form id="form1" runat="server">

10.10 Download files with ajaxified control


If you want to invoke download for a file from ajaxified control (either placed in RadAjaxPanel or ajaxified
by RadAjaxManager), you cannot use the normal
Response.WriteFile("~/Your_File");
because the xmlhttp request cannot handle this.
Instead you can use the ResponseScripts collection of the RadAjax controls to change the location header
and download the file:
RadAjaxPanel1.ResponseScripts.Add(String.Format(@"window.location.href = ""{0}"";", http://yoursite.
The ResponseScripts collection will be executed after ajax request completes.

10.11 Ajax requests queueing


By design ASP.NET AJAX Framework cancels the ongoing ajax request if you try to initiate another one prior
to receiving the response from the first one. By setting the RequestQueueSize property to a value greater
than zero, you are enabling the queueing mechanism of RadAjax, that will allow you to complete the ongoing
request and then initiate the pending requests in the control queue.

If the queue is full (queue size equals RequestQueueSize), an attempt for new ajax requests will be discarded.

The default value is 0 (queuing disabled).


protected void Page_Load(object sender, EventArgs e)
{
<RadAjaxControl>.RequestQueueSize = 3;
}
RadAjax for ASP.NET AJAX 79

11  General Troubleshooting


11.1 Known reasons for error messages
1) Receiving
Sys.WebForms.PageRequestManagerParserErrorException
The error may be received if one the same control is ajaxified by RadAjaxPanel and RadAjaxManager at the
same time. Read more about the problem in this help topic (Section 5.3.1).

2) The state information is invalid for this page and might


be corrupted
Firefox 1.5 and up uses in-memory caching for entire Web pages, including their JavaScript states, for a single
browser session. Going backward and forward between visited pages requires no page loading and the
JavaScript states are preserved. This feature, referred to by some as bfcache (for "Back-Forward Cache"),
makes page navigation very fast. This caching state is preserved until the user closes the browser.
Please refer to the Ajax, ViewState and Firefox (Section 11.6) article in this help section for more
information and workaround.

3) Dialog with the following error:


Unexpected ajax response was received from the server.
This may be caused by one of the following reasons:
- Server.Transfer.
- Custom http handler.
- Incorrect loading of an "Ajaxified" user control.
Verify that you don't get a server-side exception or any other undesired behavior, by setting the EnableAJAX
property to false.

Most often people hit this error when using Server.Transfer method. Note that some control may use this
method internally (like the ASP:LoginView control).
In order to redirect to another page in AJAX-enabled application, you should use the approaches mentioned
in Redirecting to another page (Section 10.2) help topic. In most cases Response.Redirect does the
trick. You could also check with Redirect method of RadAjax controls.
The other most possible reason is about improper loading of user controls. Our Loading user controls
(Section 10.3) help topic will help you fix the error in your code.
Additionally, if the above does not help, you could disable AJAX as suggested in the error message. This will
help you verify whether the error is AJAX usage related and if it is not, to fix any server-side error if such is
thrown.

11.2 Most Common Mistakes


My page went blank after I fired an event from dynamically loaded user control
This can happen of improper loading of User Controls. When loading user controls you need to have in mind
two things:
1. Always recreate the last loaded User Control on Page_Init/Page_Load
RadAjax for ASP.NET AJAX 80

2. Assign unique IDs to the loaded controls

If the page goes blank please check if the control is always recreated. For more info about correct loading of
user controls dynamically, please refer to this (Section 10.3) topic.

Lost ViewState
After postback/ajax request my control does not keep its last state.
This can happen if you are loading user controls and you do not assign Unique IDs to them. In this case the
framework will generate an automatic ID which can be different than the original ID and therefore the
ViewState is being lost. This is the cause for losing the last state of the control.

Postback Events not being fired


After dynamically loading User Control I cannot fire the events of any of its controls:
This is caused by improper loading as well. If the control is persisted on the page, but its events are not fired -
check if you have assigned an ID to this control. This is required by the framework to preserve the ViewState
and handle the control events.

Loading Panel does not display (UserControl with dynamically created controls scenario)
Problem: I have a user control that is populated with dynamically created controls. After I have ajax-enabled
the user control with RadAjaxPanel (RadAjaxManager) the loading panel I have specified does not display at
all when any of the dynamically created controls triggers the Ajax request (though the Ajax request itself is
completed successfully and the content is updated).
Solution: The most likely reason for this behavior is missing ID for the dynamically created controls. Please
make sure you are assigning an ID to the controls and you should experience no further problems.

11.3 AJAX And File Upload


You may experience difficulties trying to upload files with ajaxified controls. For example using the standard
<INPUT type=file> on AJAX request the uploaded files items will be empty.
Indeed, there are browser restrictions and XmlHttpRequest object limitations which makes uploading files
through AJAX requests impossible. Thus, if you want to use Telerik RadAjax controls with a page, where a
control perform uploading files, this control should make regular post-backs instead.
In a typical scenario you may have the whole page (or a part of it) nested within an RadAjaxPanel. In this
case you have to manually exclude from ajaxifying the control, which is implemented to upload files. Detailed
information how this could be achieved may be found in the "Exclude controls from ajaxifying (Section
10.5)" help topic.
Using RadAjaxManager in a page, where files are uploaded, should not be a problem. You should only take
care of not setting the correspondent control as ajaxified in Manager's AjaxSettings.
(http://www.telerik.com/demos/aspnet/Controls/Examples/Integration/Ajax/Upload/DefaultCS.aspx)

When you instantiate file upload control through ajax call (e.g. set Visible="true" or control is nested in
template control) you will need to manually add enctype="multipart/form-data" to the form as our ajax
controls (ASP.NET as well) do not update the form tag.

11.4 Control is not updated after AJAX


You have added the necessary AJAX settings, but the control is not updated as expected. There are several
possible reasons for this in cases when RadAjaxManager (Section 5.1) is used:
1) First of all, you should check whether the control is updated without using AJAX.
Just set EnableAJAX property of RadAjaxManager to false and verify your control is updated using regular
postbacks. Note in most cases the AJAX initiator control (the one set as ajaxified) will need to post back to the
RadAjax for ASP.NET AJAX 81

server, so the Ajax Manager will be able to "tranform" its postbacks to AJAX requests.

2) You should verify whether the proper AJAX initiator control is set and an user interaction concerning this
control updates the one, set as AJAX updated control.
For instance, confusion may come when using ajaxRequestWithTarget (Section 9.1) client-side function.
There, the AJAX initiator is the control, which UniqueID is set as the eventTarget argument of the function,
which may not be (as is the purpose of this function) RadAjaxPanel or RadAjaxManager controls. On the
other hand when one updates a control in AjaxRequest server side for example, the AJAX initiator should be
RadAjaxManager itself.

3) Check whether you don't try to ajaxify control placed in RadAjaxPanel using the RadAjaxManager.
For instance, if you have placed a button in RadAjaxPanel and want the button to update control outside of
the AJAX Panel, it won't be updated despite the AJAX Manager's AJAX Settings. RadAjaxPanel precedes
RadAjaxManager so the Panel will make the AJAX requests updating its content only (as this is the way that
the control is designed). More on the matter can be found here (Section 5.3.1).

4) You have ajaxified container control (like ASP:Panel) and also want to ajaxify control inside it.
Note, this can't be achieved using RadAjaxManager designer. If you have added such settings manually, indeed
some of them won't work. Here is an example where a button is expected to update two labels:

<asp:Panel ID="Panel1" runat="server" Height="51px" Width="287px">


<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="1" Height="18px" Width="224px"></asp:Label>
</asp:Panel>

<asp:Label ID="Label2" runat="server" Text="2" />

<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">


<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Panel1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Label2" />
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Label1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>

Here only one label will be updated, because only one of these settings will be taken by the Manager.
RadAjaxManager designer won't allow adding the second setting and you may simply use only one
AjaxControlID (Panel1 or Button1) to achieve your goal:

<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Label2" />
<telerik:AjaxUpdatedControl ControlID="Label1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
RadAjax for ASP.NET AJAX 82

11.5 Dropped Ajax requests from child window


In Internet Explorer, windows opened using window.open from another window, exist in the same thread as
the parent window. This is not true for Mozilla and Safari as there all child windows are opened in different
threads. Thus when you initiate an ajax request in the child window and close this window it will be aborted in
Mozilla, because closing it you actually destroy the thread which is running the ajax request. This workd in IE,
because the child window runs in the same thread as the parent and it does not destroy it when it closes.

To resolve this issue you need to create ajax requests in the context of the parent window and apply a slight
timeout on it:
<script type="text/javascript">
function OnClickHandler()
{
var thisWindow = window;
var parentWindow = window.opener;
parentWindow.setTimeout(function() { UpdateData(thisWindow, parentWindow) } , 0);
}

//this is executed in the parent window context


function UpdateData(childWindow, parentWindow)
{
var radAjaxManagerObject = parentWindow["RadAjaxManager1"];
radAjaxManagerObject.AjaxRequest(params);
childWindow.close();
}
</script>
The same goes when using our Telerik RadWindow control. You still need to force the execution in the
parentWindow, as otherwise the request will be canceled, once the window is closed:
<script type="text/javascript">
//This code is mandatory if any interaction with the "parent" RadWindow object is needed
function GetRadWindow()
{
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}

function Cancel_Clicked()
{
GetRadWindow().Close();
}

function DoParentCallback()
{
var parentWindow = window.parent;
parentWindow.setTimeout(function()
{
var radAjaxManagerObject = parentWindow["RadAjaxManager1"];
radAjaxManagerObject.AjaxRequest();
} , 0);

Cancel_Clicked();
}
</script>

Note that we use setTimeout to force execution in the parentWindow's context as it will not get closed. Another
thing to keep in mind is that one should not reference the child window in your setTimeout-invoked code as it
might have already been destroyed.
RadAjax for ASP.NET AJAX 83

11.6 Ajax, ViewState, and Firefox


Firefox 1.5 and up uses in-memory caching for entire Web pages, including their JavaScript states, for a single
browser session. Going backward and forward between visited pages requires no page loading and the
JavaScript states are preserved. This feature, referred to by some as bfcache (for "Back-Forward Cache"),
makes page navigation very fast. This caching state is preserved until the user closes the browser.
However, this Firefox feature caches the page viewstate field as well thus breaking the asynchronous postback
calls to the server in some scenarios (page refreshes, Back button navigation). For example the problem is
evident if you refresh a page in Firefox with the F5 button and not with the Ctrl+F5 combination (the former
does not clear the form values, whereas the latter does clear them) and then try to perform an Ajax request.
The result you would most certainly get is a "The state information is invalid for this page and might be
corrupted" page exception.
The Mozilla Development Center
(http://developer.mozilla.org/en/docs/Using_Firefox_1.5_caching) states that setting cache-
control: no-store in the response header of the page prevents Firefox from caching the page so you could
use the following code snippet to add a cache-control: no-store response header to any page requested by any
browser that is not Internet Explorer:
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Browser.MSDomVersion.Major == 0) // Non IE Browser?)
{
Response.Cache.SetNoStore(); // No client side cashing for non IE browsers
}
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


' Non IE Browser?
If (Request.Browser.MSDomVersion.Major = 0) Then
Response.Cache.SetNoStore() ' No client side cashing for non IE browsers
End If
End Sub

11.7 Controls Not Compatible with RadAjax for ASP.NET AJAX


The following ASP.NET controls are not compatible with partial-page updates, and are therefore not supported
inside an UpdatePanel
(http://www.asp.net/ajax/documentation/live/mref/T_System_Web_UI_UpdatePanel.aspx)
control:
 TreeView (http://msdn2.microsoft.com/en-us/k5c13faz) and Menu
(http://msdn2.microsoft.com/en-us/07b8w058) controls.
 Web Parts controls. For more information, see ASP.NET Web Parts Controls
(http://msdn2.microsoft.com/en-us/library/ab78a66e-9feb-4391-b3c3-8c07555e2308).
 FileUpload (http://msdn2.microsoft.com/en-us/ysf0192b) controls when they are used to
upload files as part of an asynchronous postback.
 GridView (http://msdn2.microsoft.com/en-us/4w7ya1ts) and DetailsView
(http://msdn2.microsoft.com/en-us/7z482d0y) controls when their
EnableSortingAndPagingCallbacks property is set to true. The default is false.
 Login (http://msdn2.microsoft.com/en-us/t863ehhh), PasswordRecovery
(http://msdn2.microsoft.com/en-us/t92zy5x0), ChangePassword
RadAjax for ASP.NET AJAX 84

(http://msdn2.microsoft.com/en-us/s1xhe282), and CreateUserWizard


(http://msdn2.microsoft.com/en-us/6s8b6814) controls whose contents have not been converted
to editable templates.
 The Substitution (http://msdn2.microsoft.com/en-us/9ze89as6) control.
 Validation controls, which includes the BaseCompareValidator
(http://msdn2.microsoft.com/en-us/z8fh4ax6), BaseValidator
(http://msdn2.microsoft.com/en-us/fczazdzk), CompareValidator
(http://msdn2.microsoft.com/en-us/d7365skb), CustomValidator
(http://msdn2.microsoft.com/en-us/303z9x0x), RangeValidator
(http://msdn2.microsoft.com/en-us/ccs7ftb0), RegularExpressionValidator
(http://msdn2.microsoft.com/en-us/sffh7429), RequiredFieldValidator
(http://msdn2.microsoft.com/en-us/ycxs7t4x), and ValidationSummary
(http://msdn2.microsoft.com/en-us/xd4c894c) control.

See a full list of controls, not compatible with RadAjax for ASP.NET AJAX from the official MS AJAX
documentation here (Section 10.6).

11.8 Error Handling For Ajax Requests


We did not implement our own error handling for RadAjax, as the MS AJAX framework already takes care of
that. During partial-page rendering, you can handle errors by doing the following:
 Set the AllowCustomErrorsRedirect
(http://www.asp.net/ajax/documentation/live/mref/P_System_Web_UI_ScriptManager_AllowCusto
property, which determines how the custom error section of the Web.config file is used when an error
occurs during an asynchronous postback.
 Handle the ScriptManager
(http://www.asp.net/ajax/documentation/live/mref/T_System_Web_UI_ScriptManager.aspx)
control's AsyncPostBackError
(http://www.asp.net/ajax/documentation/live/mref/E_System_Web_UI_ScriptManager_AsyncPostB
event, which is raised when there is a page error during an asynchronous postback.
 Set the AsyncPostBackErrorMessage
(http://www.asp.net/ajax/documentation/live/mref/P_System_Web_UI_ScriptManager_AsyncPostB
property, which is the error message that is sent to the browser.
RadAjax for ASP.NET AJAX 85

12  Performance
12.1 Optimizing client-side performance
The RadAjaxManager control allows you to easily create settings that update many controls on the page.
Having a large number of updated controls can both help with a performance problem by rendering smaller
portions of the page and worsen the situation by triggering unnecessary DOM layout updates. Dealing with
such a performance problem will require actions specific for the current scenario.

12.1.1 Optimizing DOM updates


Most of the slowdown happens when updating multiple controls in a table element. Every DOM update
triggers a set of layout recalculations that take up unneeded time. Take the following HTML for example:
<div id="Header" style="width: 100%;" runat="server">
<table id="Table3" cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td>
<asp:Label ID="lblStatus" runat="server" />
</td>
<td>&nbsp;</td>
<td style="height: 25px">
<asp:Label ID="lblMessage" runat="server" />
</td>
</tr>
</table>
</div>

Having two AjaxSetting's for both labels will cause two DOM element updates: the spans rendered by
lblStatus and lblMessage respectively. This will make the browser recalculate the table size twice. The
process can be optimized by updating the TABLE or the outer DIV element. Updating the Header control will
update both labels and will trigger one DOM update only.
Prohibitively bad performance is usually the result of updating controls that are placed deeply inside nested
tables. Most browsers are slow when rendering elements with percentage dimensions (typically width or
height of 100%), so another way to optimize this is to switch to sizes in pixels. Another possible solution is
to use fixed table layout by setting an HTML table's CSS style property table-layout to fixed:
<style type="text/css">
#Header table
{
table-layout: fixed;
}
</style>
You will need to define width and <colgroup> and <col> elements for your table when using fixed table layout.
Check Microsoft's HTML optimization article
(http://msdn.microsoft.com/workshop/author/perf/perftips.asp) for other suggestions on
improving page and table performance..

12.1.2 Other performance boosters


Having too many CSS stylesheet inclusions or too large CSS style blocks in your <head> tag can be slow to
update too. You can try switching Telerik RadAjax's head update feature off if you do not load CSS-rich
controls in Ajax requests. You can do that by setting the EnablePageHeadUpdate property to false.
Most browsers render documents a lot slower when operating in quirks mode. Try switching to strict mode by
specifying a doctype for your document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
RadAjax for ASP.NET AJAX 86

13  RadAjax Appearance and Styling


13.1 Controlling Appearance
The principal visual aspect of RadAjax is the RadAjaxLoadingPanel
(RadAjaxLoadingPanelOverview.html) that displays during updating. You can control the appearance of
RadAjaxLoadingPanel (RadAjaxLoadingPanelOverview.html) by the following methods:
 Modify the markup within the <telerik:RadAjaxLoadingPanel></telerik:RadAjaxLoadingPanel> tags.
 Change the image that displays in the loading panel. RadAjax ships with a number of pre-defined
animated "gif" images. Change the <src> tag path to one of the gifs in the installation directory:
"\Telerik\RadControls for ASP.NET AJAX Q2 2008\Skins\Default\Ajax"
 RadAjaxLoadingPanel (RadAjaxLoadingPanelOverview.html) descends from
System.Web.UI.Panel and provides properties for back color, font and other properties. Typically you
would use the markup and loading image to style your loading panel, but these Panel properties can also
be used.

[ASP.NET] RadAjaxLoadingPanel
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server"
BackColor="Honeydew" BorderColor="Green" BorderStyle="Dotted" BorderWidth="3px"
ForeColor="Blue" MinDisplayTime="1000" >
<img alt="Loading..."
src='<%= RadAjaxLoadingPanel.GetWebResourceUrl(Page,
"Telerik.Web.UI.Skins.Default.Ajax.loading3.gif") %>'
style="border: 0px;" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</telerik:RadAjaxLoadingPanel>
RadAjax for ASP.NET AJAX 87

14  RadAjax Server-Side Programming


14.1 RadAjaxControl Properties
 EnableAJAX: When the EnableAJAX property is True (the default), all requests (controls either within
the RadAjaxPanel Template or managed by the RadAjaxManager) are handled via AJAX. If not checked,
requests are handled in the legacy postback manner.
 EnableHistory: When EnableHistory property is True (the default is False), browser history is
enabled even when using AJAX. The forward and back buttons of the browser work as expected (IE
browser only).
 EnablePageHeadUpdate: When the EnablePageHeadUpdate is True (the default), the Page <Head>
element can be modified during AJAX updates. This is especially useful, when you have initially invisible
control or you are loading the control dynamically on ajax request.
 IsAjaxRequest: This property is true when the current request is through AJAX and false when the
request is a standard postback. In the example below "Button1" has been configured to be AJAX-enabled
and the alert will display "True". Clicking "Button2" will display "False".
[C#] Using IsAjaxRequest
protected void Button1_Click(object sender, EventArgs e)
{
RadAjaxManager1.Alert(RadAjaxManager1.IsAjaxRequest.ToString());
}
protected void Button2_Click(object sender, EventArgs e)
{
RadAjaxManager1.Alert(RadAjaxManager1.IsAjaxRequest.ToString());
}

[VB] Using IsAjaxRequest


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
RadAjaxManager1.Alert(RadAjaxManager1.IsAjaxRequest.ToString())
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
RadAjaxManager1.Alert(RadAjaxManager1.IsAjaxRequest.ToString())
End Sub

[ASP.NET] AjaxSettings for Button1 Only


<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Button1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Label1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
&nbsp; &nbsp;
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:Label ID="Label1" runat="server" Text="Label"></ asp:Label>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click"
Text="Button" /></div>

 ResponseScripts: This collection of strings contain JavaScript that you want to execute when the
response returns to the browser. In the example below an "alert()" JavaScript function is added to the
collection. Also see below for the rendered HTML results showing the call to alert() near the end of the
HTML.
RadAjax for ASP.NET AJAX 88

[C#] Assigning ReponseScripts


protected void Button2_Click(object sender, EventArgs e)
{
RadAjaxManager1.ResponseScripts.Add("alert('this fires after the
response');");
}
[VB] Assigning ReponseScripts
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
RadAjaxManager1.ResponseScripts.Add("alert('this fires after the response');")
End Sub
[HTML] Rendered HTML and JavaScript After Assigning ResponseScripts
...
<script type="text/javascript">
<!--
setTimeout(function(){alert('this fires after the response');}, 0);Sys.Application.init
Sys.Application.add_init(function() {
$create(Telerik.Web.UI.RadAjaxManager, {"ajaxSettings":[{InitControlID : "Button1",U
[{ControlID:"Label1",PanelID:""}]}],"clientEvents":
{OnRequestStart:"",OnResponseEnd:""},"defaultLoadingPanelID":"","enableAJAX":true,"enab
[],"styles":[],"uniqueID":"RadAjaxManager1"}, null, null, $get("RadAjaxManager1"));
});
// -->
</script>
</form>
</body>
</html>

14.2 OnAjaxRequest event
The AjaxRequest event occurs when triggered by the client-side AjaxRequest() (client-side-
basics.html) function or the server-side RaisePostBackEvent() (server-methods.html) method. The
event may not be canceled. The AjaxRequest event handler receives a single string argument.
The example below demonstrates AjaxRequest triggered from both the client and server. An a HTML input
button and a standard ASP.NET button are defined in the example. The HTML input button triggers a function
that calls the client-side AjaxRequest() (client-side-basics.html). The ASP.NET button triggers a server-
side OnClick event that in turn calls the RaisePostBackEvent() (server-methods.html) method.

Example
[ASP.NET] Using Client and Server AjaxRequest

<head runat="server">
<title>RadAjax for ASP.NET AJAX</title>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function clientClick()
{
var ajaxManager = $find("<%= RadAjaxManager1.ClientID %>");
ajaxManager.ajaxRequest("client");
}
</script>
</telerik:RadCodeBlock>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
RadAjax for ASP.NET AJAX 89

<telerik:RadAjaxManager
ID="RadAjaxManager1"
runat="server"
OnAjaxRequest="RadAjaxManager1_AjaxRequest">
</telerik:RadAjaxManager>
<asp:Button ID="btnServer"
runat="server"
Text="Make server AjaxRequest"
OnClick="btnServer_Click" />
<input
id="btnClient"
type="button"
value="Make client AjaxRequest"
onclick="clientClick();" />
</div>
</form>
</body>
[C#] Using RaisePostBackEvent() and Handling AjaxRequest Event
using System;
namespace RadAjax_RaisePostbackEvent
{
public partial class _Default : System.Web.UI.Page
{
protected void btnServer_Click(object sender, EventArgs e)
{
RadAjaxManager1.RaisePostBackEvent("server");
}
protected void RadAjaxManager1_AjaxRequest(object sender,
Telerik.Web.UI.AjaxRequestEventArgs e)
{
RadAjaxManager1.Alert("AjaxRequest raised from the " + e.Argument);
}
}
}
[VB] Using RaisePostBackEvent() and Handling AjaxRequest Event
Imports System
namespace RadAjax_RaisePostbackEvent
Public Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub btnServer_Click(ByVal sender As Object, ByVal e As EventArgs)
RadAjaxManager1.RaisePostBackEvent("server")
End Sub
Protected Sub RadAjaxManager1_AjaxRequest(ByVal sender As Object, ByVal e As
Telerik.Web.UI.AjaxRequestEventArgs)
RadAjaxManager1.Alert("AjaxRequest raised from the " + e.Argument)
End Sub
End Class
End Namespace

14.3 OnAjaxSettingCreating event
The AjaxSettingCreating event occurs just before an AjaxSetting is added to the RadAjaxManager
AjaxSettings collection. The event can be triggered by the AjaxSettings configured at design time, as they are
about to be instantiated, or at run-time in response to AddAjaxSetting(). The event can be cancelled.
The AjaxSettingCreating event handler receives two arguments:
1. The RadAjaxManager control that owns the AjaxSettings collection that the setting is being added to.
This argument is of type object, but can be cast to the RadAjaxManager type.
RadAjax for ASP.NET AJAX 90

2. A AjaxSettingCreatingEventArgs object with the following properties:


 Canceled: This boolean property can be set true to abandon creating the AjaxSetting and will
prevent the AjaxSettingCreated (Section 14.3) event from firing.
 Initiator: A reference to the object that triggered the AJAX request.
 Updated: A reference to the object that will be updated by the AJAX request.
 UpdatePanel: A reference to the underlying MS AJAX UpdatePanel.

Example
[C#] AjaxSettingCreating
protected void RadAjaxManager1_AjaxSettingCreating(object sender,
AjaxSettingCreatingEventArgs e)
{
e.Canceled = (e.Initiator == Button1) & (e.Updated == Label1);
}
[VB] AjaxSettingCreating
Protected Sub RadAjaxManager1_AjaxSettingCreating(ByVal sender As Object, ByVal e
As AjaxSettingCreatingEventArgs)
e.Canceled = (e.Initiator = Button1) And (e.Updated = Label1)
End Sub

14.4 OnAjaxSettingCreated event
The AjaxSettingCreated event occurs after an AjaxSetting is added to the RadAjaxManager AjaxSettings
collection. The event can be triggered by the AjaxSettings configured at design time, as they are instantiated, or
at run-time after AddAjaxSetting() is called. The event cannot be cancelled.
The AjaxSettingCreated event handler receives two arguments:
1. The RadAjaxManager control that owns the AjaxSettings collection that the setting is being added to.
This argument is of type object, but can be cast to the RadAjaxManager type.
2. A AjaxSettingCreatedEventArgs object with the following properties:

 Initiator: A reference to the object that triggered the AJAX request.


 Updated: A reference to the object that will be updated by the AJAX request.
 UpdatePanel: A reference to the underlying MS AJAX UpdatePanel.

Example
[C#] AjaxSettingCreated
protected void RadAjaxManager1_AjaxSettingCreated(object sender,
AjaxSettingCreatedEventArgs e)
{
RadAjaxManager1.Alert(
"AjaxSetting Created for initiator " + e.Initiator.ClientID +
" and updated control " + e.Updated.ClientID);
}
[VB] AjaxSettingCreated
Protected Sub RadAjaxManager1_AjaxSettingCreated(ByVal sender As Object, ByVal e
As AjaxSettingCreatedEventArgs)
RadAjaxManager1.Alert("AjaxSetting Created for initiator " +
e.Initiator.ClientID + " and updated control " + e.Updated.ClientID)
End Sub

14.5 RadAjaxControl Methods
RadAjax for ASP.NET AJAX 91

RadAjaxManager and RadAjaxPanel both descend from RadAjaxControl that introduces the following
methods:
 Alert: This convenient method executes a JavaScript alert() on the client. Alert() takes a single string
parameter for text to be displayed in the alert.
[C#] Using Alert
RadAjaxManager1.Alert("Please save your changes.");
[VB] Using Alert
RadAjaxManager1.Alert("Please save your changes.")

 FocusControl: This method places focus on a specified control. FocusControl() takes a single parameter
that can be the id of the control to focus on or an object reference to the control to focus on.
[C#] Using FocusControl
RadAjaxManager1.FocusControl(Button1);
[VB] Using FocusControl
RadAjaxManager1.FocusControl(Button1)

 GetAjaxEventReference: This method produces client side code that invokes the AjaxRequest()
(client-side-basics.html) method.
[C#] Using GetAjaxEventReference
RadAjaxManager1.GetAjaxEventReference(Button1.ClientID);
//... returns "$find("RadAjaxManager1").ajaxRequest(" Button1");"
[VB] Using GetAjaxEventReference
RadAjaxManager1.GetAjaxEventReference(Button1.ClientID)
'... returns "$find("RadAjaxManager1").ajaxRequest("Button1");"

 RaisePostBackEvent: This method triggers a server-side AjaxRequest


(ServerSideAjaxRequest.html) event and allows you to pass a single string parameter to the event.
AjaxRequest can also be triggered by the client-side ajaxRequest (client -side-basics.html)
() function.
[C#] Using RaisePostBackEvent
protected void Button1_Click(object sender, EventArgs e)
{
RadAjaxManager1.RaisePostBackEvent(DateTime.Now.ToString());
}
protected void RadAjaxManager1_AjaxRequest(object sender,
Telerik.Web.UI.AjaxRequestEventArgs e)
{
Label1.Text = e.Argument;
}
[VB] Using RaisePostBackEvent
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
RadAjaxManager1.RaisePostBackEvent(DateTime.Now.ToString())
End Sub
Protected Sub RadAjaxManager1_AjaxRequest(ByVal sender As Object, ByVal e As
Telerik.Web.UI.AjaxRequestEventArgs) _
Handles RadAjaxManager1.AjaxRequest
Label1.Text = e.Argument
End Sub

 Redirect: This method navigates the browser to another web page. The method passes a single string
parameter which is the URL to navigate to.
[C#] Using Redirect
RadAjaxManager1.Redirect("http://www.telerik.com (http://www.telerik.com/)");
RadAjax for ASP.NET AJAX 92

[VB] Using Redirect


RadAjaxManager1.Redirect("http://www.telerik.com")

14.6 Server Side Events


RadAjaxManager and RadAjaxPanel both descend from RadAjaxControl. RadAjaxControl introduces the
following events:
 AjaxRequest (ServerSideAjaxRequest.html): This event is fired in response to a client-side
ajaxRequest() (client-side-basics.html) function or the server-side RaisePostBackEvent()
(server-methods.html) method.
 AjaxSettingCreating (ServerSideAjaxSettingCreating.html): This event occurs just before an
AjaxSetting is added to the AjaxSettings collection.
 AjaxSettingCreated (ServerSideAjaxSettingCreated.html): This event event occurs after an
AjaxSetting is added to the AjaxSettings collection
RadAjax for ASP.NET AJAX 93

15  RadCodeBlock and RadScriptBlock

RadCodeBlock and RadScriptBlock are used to allow server and client script to work well together with
AJAX updates.

RadCodeBlock
RadCodeBlock should be used when you have server code blocks placed within the markup (most often
some JavaScript functions accessing server controls). RadCodeBlock prevents the server error:
System.Web.HttpException: The Controls collection cannot be modified because the control contains code
blocks (i.e. <% ... %>).
For more background on this issue see Understanding how expressions render and why
Controls.Add() doesn't work (http://www.west-wind.com/WebLog/posts/6148.aspx).
The way code blocks (server script within "<%= %>" tags) are implemented in ASP.NET may interfere with
the RadAjaxManager render interception mechanism. RadCodeBlock is used to isolate the code block
preventing the error from appearing.

[ASP.NET] Using RadCodeBlock


<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script language="javascript" type="text/javascript">
function AjaxReq(args)
{
$find("<%= RadAjaxPanel1.ClientID %>").ajaxRequestWithTarget("<%=
Button1.UniqueID %>", '');
}
</script>
</telerik:RadCodeBlock>

RadScriptBlock
RadScriptBlock is used where you have JavaScript that evaluates after an AJAX request, for example when
the content of RadAjaxPanel is updated asynchronously. RadScriptBlock also can be used like RadCodeBlock
to handle server code blocks (<% ... %>).
RadScriptBlock wraps JavaScript where the JavaScript is located in an updating area. The example below
shows a RadScriptBlock within a RadAjaxPanel.

[ASP.NET] Using RadScriptBlock


<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
<asp:Panel ID="Panel1" runat="server">
<asp:Button ID="Button1" runat="server" />
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
alert(1);
</script>
</telerik:RadScriptBlock>
</asp:Panel>
</telerik:RadAjaxPanel>
RadAjax for ASP.NET AJAX 94

Index
OnAjaxRequest event, 88-89
Achieve interaction between AJAX Panels, 48-49
Add AjaxSettings programmatically, 31-32
AJAX And File Upload, 80
AJAX Loading Panel, 53-54
AJAX Manager, 29-31
AJAX Manager Designer does not locate all controls, 43-44
AJAX Manager Proxy, 51-52
AJAX Panel, 46-48
Ajax requests queueing, 78
Ajax, ViewState, and Firefox, 82-83
Ajaxified control still postbacks, 43
Ajaxify particular templated GridView buttons, 38-40
Ajaxifying controls wrapped in RadAjaxPanel and added to AJAX Manager settings, 41-43
Assign different Client-events for different controls, 67
Back and Forward browser buttons (browser history), 28
Cancel AJAX request, 65
Center LoadingPanel on the Screen, 57-58
Centralized Management of AJAX Relations, 10-12
Change mouse cursor on AJAX update, 67-68
Changes and backwards compatibility, 24-27
Client confirmation and AJAX, 65-66
Client side Events, 61
Client-Side API, 59-61
Codeless Development, 8-10
Control is not updated after AJAX, 80-82
Controlling Appearance, 86
Controls Not Compatible with RadAjax for ASP.NET AJAX, 83-84
Current RadAjax Limitations, 27-28
Design Time of RadAjax Controls, 15-18
Disable AJAX when client browser does not support it, 76
Disable controls during AJAX, 76 -77
Download files with ajaxified control, 78
Dropped Ajax requests from child window, 82
Error Handling For Ajax Requests, 84
Exclude controls from ajaxifying, 73-75
Executing custom javascript code after AJAX update, 64-65
Forcing postback, 66-67
Frequently Asked Questions, 69
RadAjax for ASP.NET AJAX 95

Getting started: AJAX-enable a scenario through RadAjaxManager and LoadingPanel, 18-21


How RadAjax Works: Controls And Configuration, 14-15
How to use Css Conditional Comments with Ajax, 77-78
Incompatible controls and updating 3rd party controls with Telerik RadAjax, 75-76
Intuitive Way for Defining AJAX Relations, 6-8
Known reasons for error messages, 79
Layout problem: Updated controls on new line, 44-45
Load user controls, 70-72
Manually add an AJAX request to a client-side event of an HTML element, 72-73
MasterPages: ajaxify and update controls in master and content page, 35-37
MasterPages: initiating requests from one ContentPlaceHolder and loading/updating controls
in another, 37-38
Most Common Mistakes, 79-80
No Modifications to Your Application, 3-6
OnAjaxSettingCreated event, 90
OnAjaxSettingCreating event, 89-90
OnRequestStart, 63-64
OnResponseEnd, 64
Optimizing client-side performance, 85
Pass more than one argument, 66
queue, 78
RadAjax and MasterPage, 34-35
RadAjax and WebUserControls, 32-34
RadAjax for ASP.NET vs RadAjax for ASP.NET AJAX, 22-23
RadAjaxControl Methods, 90-92
RadAjaxControl Properties, 87-88
RadAjaxManager Client Object, 61-62
RadAjaxPanel Client Object, 62-63
RadCodeBlock and RadScriptBlock, 93
Redirecting to another page, 69-70
Scroll to top after AJAX, 49-50
Server Side Events, 92
Server-Side OverView, 21
SharePoint WebPart: Dynamically added manager is missing in Page.Controls, 45
Show and hide loading panel explicitly, 54-55
Show RadAjaxLoadingPanel on initial page load, 55-56
Show the loading panel next to AJAX initiator, 56-57
Update in composite control, 40-41
What is AJAX?, 1-2
What's New in RadAjax for ASP.NET AJAX, 23-24

Vous aimerez peut-être aussi