Using The Update Panel Control

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 110

Using the UpdatePanel Control in Visual Studio

Web Developer 2010


Microsoft Server-Side AJAX Framework consists of one main
control: the UpdatePanel Control. The UpdatePanel Control
enables you to update a portion of a page without updating the
entire page. In other words it enables you to performance partial
page rendering.
If you're ever in the market for some great Windows web hosting, try
Server Intellect. We have been very pleased with their services and most
importantly, technical support.

Step 1

Let’s open a new website and name it UpdatePanelSimple.


Hopefully by now you will have remembered how to open a new
website. If not you can check in the beginner tutorials.

The <asp:UpdatePanel> tag has two childtags - the


ContentTemplate and the Triggers tags. The ContentTemplate tag
is required, since it holds the content of the panel. The content
can be anything that you would normally put on your page, from
literal text to web controls. The Triggers tag allows you to define
certain triggers which will make the panel update its content. The
following example will show the use of both childtags.

Step 2 I have copied the code over and go ahead and copy it over
to your source code as it looks.
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="EmailForm.WebForm1" %>

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


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>UpdatePanel Simple</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat ="server"/>

Page Time: <%= DateTime.Now.ToString("T") %>


<br /><br />

<asp:UpdatePanel
id="up1"
runat="server">
<ContentTemplate>
UpdatePanel Time <%= DateTime.Now.ToString("T") %>
<br />
<asp:Button
id="btn"
Text="Update"
runat="server" />
</ContentTemplate>
</asp:UpdatePanel>

<div>

</div>
</form>
</body>
</html>

As you can see in the code or when switch over to design view
you will see we have added a ScriptManager , and an UpdatePanel
as well. The UpdatePanel contains a single Button Control, when
you click the button only the content contained in the
UpdatePanel control is refreshed.

The Page in the listing displays the current time both inside and
outside the Update Control Panel Control. When you click the
button, only the time within the UpdatePanel control is refreshed.

If you're looking for a really good web host, try Server Intellect -
we found the setup procedure and control panel, very easy to
adapt to and their IT team is awesome!

In our Next tutorial Regarding the Microsoft AJAX UpdatePanel we


will take a more realistic approach that just begs for AJAX control
over it.

Simple Introduction to using Jquery in ASP.NET


This tutorial assumes you understand the basics of JavaScript as well as
understanding the basics of Microsoft Visual Studio Web Developer
2010. This tutorial will go over how to use some basic Jquery to show
some content on a page.

If you're ever in the market for some great Windows web hosting, try
Server Intellect. We have been very pleased with their services and most
importantly, technical support.

Step 1 – Add the button to the page


1) Drag a button control onto the page from the toolbox
2) For the purpose of this tutorial we are giving the button an id of
showButton

<asp:Button ID="showButton" runat="server" Text="Show Message" />


Step 2 – Add the Message Div
1) Add a new div on the page with an id of message
2) Add a display:none style to it
3) Inside add any kind of semantic tag you would like
a. We chose to add an <h1> tag
4) Insert whatever text you will want to display when the button is
clicked

<div id="message" style="display: none">


<h1>
This is the Jquery fade in. This is a simple introduction to using Jquery in your
applications!
</h1>
</div>

Step 3 – Add the script call to the default.aspx


1) Add the Jquery library to your document
a. For the purposes of this tutorial we will be using the
Microsoft library

<script src=http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js
type="text/javascript"></script>

Step 4 – Add custom JavaScript to enable to action of the


message
1) First we will check to enable to dom and make sure everything is
functioning

$(domReady);

2) We will now run a function based off the domReady call that will
show the message when the user clicks on the button

function domReady() {
$('#showButton').click(showMessage);
}

3) Lastly, We will create the showMessage function which will


provide how the message appears when being displayed to the
user.
a. For the purposes of this tutorial we are going to slowly
fade in the content so everyone will be able to see how this
functions.

function showMessage() {
$('#message').fadeIn('slow');
}

4) This should go without saying, but make sure you are including
all of this inside of a script tag with the declaration for JavaScript.
If this does not make sense to you, than you can reference the
source files which have been included
a. It is always good practice to build your site JavaScript in an
external file, but for the purposes of this tutorial we have
built it inline so it is easier to understand how the
application is working

Congratulations, you have built your first application using the


JavaScript library of Jquery. Hopefully this tutorial has given you a peek
into what is possible with this library and the endless possibilities within
ASP.NET applications you can use it for.

If you're looking for a really good web host, try Server Intellect -
we found the setup procedure and control panel, very easy to
adapt to and their IT team is awesome!

This tutorial will cover how to handle the Command Event property
using ASP.NET C#

In this tutorial we will cover how the handle Command Event by


implementing two button controls to sort; ascending and
descending. In this case, the two button controls will list items
displayed by the BulletedList control when clicked.

Here is a snapshot of how the application will look like:


Need help with Windows Dedicated Hosting? Try Server Intellect I'm
a happy customer!

To start, open Visual Studio 2008. File > New > Web site > ASP.NET
Web site and name it sort or whatever you want. Make sure that you
include using System.Collections.Generic;

From the Design View, drag over two button controls and assign
them the values listed below:

<asp:Button ID="btnSortAsc"
Text="Sort ASC"
CommandName="Sort"
CommandArgument="ASC"
OnCommand="Sort_Command"
runat="server" />
asp:Button ID="btnSortDESC"
Text="Sort DESC"
CommandName="Sort"
CommandArgument="DESC"
OnCommand="Sort_Command"
runat="server" />

Notice how both Button controls include CommandName and


CommandArgument properties. Additionally, we have both Button
controls wired to the same Sort_Command() event handler.

Next, from the Design View locate the standard tab of the Toolbox,
and drag over a bulleted list. Assign it the same value as below:

<asp:BulletedList ID="bltPeople" runat="server" />

Switch to your code behind and let’s add some logic for these event
handlers.

First, lets populate the page when it loads with these values below.
So within the Page_Load event:

protected void Page_Load(object sender, EventArgs e)


{
people.Add("Mike");
people.Add("Edward");
people.Add("Thomas");
}

This lets our page know that we have a list of data and we need to
add things to it.
If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

Next, we need to add an event handler that checks the


CommandName and CommandArguement properties when
determining how the elements in the BulletedList should be sorted.

protected void Sort_Command(object sender,


CommandEventArgs e)
{
if (e.CommandName == "Sort")
{
switch (e.CommandArgument.ToString())
{
case "ASC": people.Sort(SortASC);
break;
case "DESC": people.Sort(SortDESC);
break;
}
}
}

Above we created a Command that will determine which function to


call during data organization.

The following part of our script is required in order to work correctly.


The funciton Page_PreRender() lets the page right before it starts
processing that our bltPeople.DataSource = people;. Keep in mind
that when we created: private List people = new List(); that we told
our page that our list of strings is going to be used in our Bulleted
List.

void Page_PreRender()
{
bltPeople.DataSource = people; bltPeople.DataBind();
}

Finally, we have our sort functions. The Sort_Command was


designed to handle both button requests for ASC and DESC order.
Since we know what we want to do with each function we simply
add a basic String.Compare statement that compares two variables
and returns them in a given sequence order.

int SortASC(string x, string y)


{
return String.Compare(x, y);
}
int SortDESC(String x, String y)
{
return String.Compare(x, y) * -1;
}

If you're ever in the market for some great Windows web hosting,
try Server Intellect.We have been very pleased with their services
and most importantly, technical support.

This tutorial will use Multiple Popup Controls to populate a textbox in


ASP.NET 3.5 AJAX Web App. C#

In this tutorial we will use two PopupControl extender’s from the


AJAX Control Toolkit which offers an easy way to trigger a popup if
any other control gets activated.

Here is a snapshot of the Popup Control extender:

Need help with Windows Dedicated Hosting? Try Server Intellect I'm
a happy customer!

To start, open Visual Studio 2008. File > New > Web Site > ASP.NET
Web site and name it MultPopupCntrl or whatever you would like.

From the Design View of the default.aspx page, locate the Microsoft
AJAX extensions tab of the toolbox and double-click the
ScriptManager. Then from the same tab double-click the
UpdatePanel as well.

Now drag two Textboxes over to the page within the UpdatePanel.
Name the first textbox txtBegin, and the second txtEnd. As soon as
you are done setting the textbox properties, type in “Begin Date”
and “End Date” in front of each corresponding textbox.

<div class="style1">
Begin Date:
<asp:TextBox ID="txtBegin" runat="server">
</asp:TextBox>
End Date:
<asp:TextBox ID="txtEnd" runat="server">
</asp:TextBox> </div>

Next, from the toolbox drag over a Panel control and place it inside
of the UpdatePanel and name it pCal. Within the Panel control you
just implemented drag and drop a Calendar control inside of it and
name it cal.

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


<ContentTemplate>
<asp:Panel ID="pCal" runat="server">
<asp:Calendar ID="cal"
OnSelectionChanged="cal_SelectionChanged"
runat="server" Style="text-align: center"> </asp:Calendar>

</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>

Highlight the every control on the page and center, justify them.
The Design View should look like this:

Switch to your source view.

Within the calendar tag, add an OnSelectionChanged element.

<asp:Calendar ID="cal"
OnSelectionChanged="cal_SelectionChanged"
runat="server" Style="text-align: center"> </asp:Calendar>

Then locate the AJAX Toolkit and drag over two


PopupControlExtender’s below and outside the UpdatePanel. Then
add a TargetControlID and assign it the value txtBegin and txtEnd
respectively. This allows the calendar control to place the value
selected by the user inside of the specific textbox.

Next, add a PopupControlID for each PopupControlExtender and


pass it the value pCal of the Calendar controlID. In this case you can
position it at the Bottom.

<asp:PopupControlExtender ID="PopupCntrlEx1"
TargetControlID="txtBegin" PopupControlID="pCal"
Position="Bottom" runat="server" />
<asp:PopupControlExtender ID="PopupCntrlEx2"
TargetControlID="txtEnd" PopupControlID="pCal"
Position="Bottom" runat="server" />

If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

The TargetControlID attribute provides the ID of the control tied to


the extender. The PopupControlID attribute contains the ID of the
popup panel. For this instance, both extenders show the same
panel, but both panels are possible as well.

Save and Run. Now whenever you click within a text field, a
calendar will appear, allowing you to select a date.

Next we need to add some logic to the code behind in order to


populate the correct dates for the correct textbox. This is the reason
that we added the OnSelectionChanged to the calendar control.
Switch to your default.aspx.cs page and add this logic to the
cal¬_OnSelectionChanged() event.

protected void cal_SelectionChanged(object sender,


EventArgs e)
{
if (txtBegin.Text == "")
{
txtBegin.Text = cal.SelectedDate.ToShortDateString();
}
else
{
txtEnd.Text = cal.SelectedDate.ToShortDateString();
}
}

The PopupControl is an ASP.NET AJAX extender that can be added to


any control in order to open a popwindow that displays additional
content, including ASP.NET server controls, HTML elements, etc. In
this case, we made the popup window interactive within an ASP.NET
AJAX UpdatePanel, this way it could be able to perform complex
server-based processing (includeing postbacks) without affecting
the rest of the page.

Server Intellect assists companies of all sizes with their hosting


needs by offering fully configured server solutions coupled with
proactive server management services. Server Intellect specializes
in providing complete internet-ready server solutions backed by
their expert 24/365 proactive support team.

Learn how to use the Timer Control in ASP.NET 3.5 AJAX C#

This tutorial will demonstrate the use of the timer control which
comes as a part of the Microsoft AJAX Extensions. C#

The timer control is great for when you have an area of your user
interface that you want to be dynamically updated based on some
periodic interval, opposed to when you have some interaction with
the user.

The Timer, a server control, embeds a JavaScript component into a


Web page. It’s kind of simple, after the interval property of the
Timer control is defined, the JavaScript component will then initiates
a postback from the browser when that property expires.

Here is a snapshot of what the page will look like:

Try Server Intellect for Windows Server Hosting. Quality and


Quantity!

A good scenario could be updating a stock symbol, or maybe


periodically pulling an RSS Feed. For this instance, we will build a
demo that periodically updates a banner ad for a Web site page.
Before we get started you can go into Microsoft Paint and create
three different color rectangles that we be used as “banner
advertisements” and set their properties to 460 x 60 pixels, and
name them banner_1.gif, banner_2.gif, banner_3.gif. Also, be sure to
include your ajax toolkit .dll file onto the project. Right-click on the
name of the project in the Solution Explorer and choose "Add
Reference".

To start, open Visual Studio. File > New > Web site > ASP.NET Web
site and name it tmrCntrl or whatever you want.

Switch to Design View. Locate the solution explorer and right-click


on the name of your project. Choose create new Folder and name it
banners. Place all your banners that you just created into this folder.

From Design View locate the AJAX extensions tab of the toolbox and
double-click ScriptManager (this must be included when you use a
Timer control). Then double-click on the Timer control located within
that same tab. Underneath these two controls place an UpdatePanel
where you will place your banner advertisements.

Next, above and below the UpdatePanel add some text like; ”Here is
some sample content that wraps around and Update Panel”. Lastly,
add a standard ASP.NET Image control within the UpdatePanel to
contain our banner ad. Then we need to provide a banner ad by
default, so we need to locate the properties window and click on the
ImageUrl and statically select the first banner in your banner folder.

The markup should stzrt looking similar to this:

<head id="Head1" runat="server">


<title>Displaying a Timer on an ASP.NET Page</title>
</head>
<body>
<form id="myForm" runat="server">
<asp:ScriptManager ID="smScriptManager"
runat="server" />
<asp:Timer ID="tmrTimer" OnTick="tmrTimer_Tick"
runat="server" Interval="1500" />
<br />
<hr />
<br /> This is where the content is in your site. These
banners can wrap...
<br />
<asp:UpdatePanel ID="bpBannerPanel" runat="server"
UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tmrTimer" />
</Triggers>
<ContentTemplate>
<asp:Image ID="biBannerImage" runat="server"
ImageUrl="~/banners/banner_1.gif" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<div> around the content of your site..
<br />
</div>
</form>
</body>
</html>

Now we need to specify the interval of the timer control and set it to
about 1.5 seconds or a value of 1500. Also, we need to specify an
onTick event handler for our code behind.

We need to tell the UpdatePanel that in addition to its standard


behavior we want to include a triggers collection and wire up an
async postback trigger to the timer event that we just defined.

Important! When a timer control is included inside an UpdatePanel


control, it automatically works as a trigger for the UpdatePanel
unless; you override that behavior by setting the ChildrenAstriggers
property of the UpdatePanel control to false.

If you're ever in the market for some great Windows web hosting,
try Server Intellect.We have been very pleased with their services
and most importantly, technical support.

Be sure to set the Interval property to specify how often these


postbacks will occur. Do not forget to also set the Enabled property
to turn the Timer on or off. The Interval property is defined in
milliseconds.

When a timer control is in an UpdatePanel control, the JavaScript


timing component is replenished only when each postback finishes.
For this reason, the timed interval does not start until the page
returns from the postback. For example, let’s say the interval
property is set to 120,000 milliseconds (2 min) but each postback
takes 3 seconds to complete, therefore the next postback will
actually take 2.3 minutes to complete after the previous postback.

After a postback is initiated by the Timer control, it then raises the


Tick event on the server. You can create an event handler for the
Tick event to perform actions when the page is posted to the server.

Switch to your code behind. This is where we can configure which


banner ad we will display next. In this case we will just grab a
random banner ad. Now we can use a random number integer value
to select which one of the banner ad’s we want to display next.
Check it out below:
protected void tmrTimer_Tick(object sender, EventArgs e)
{
Random RandomClass = new Random();
int n = RandomClass.Next(1, 4);
biBannerImage.ImageUrl =
System.String.Concat("banners/Banner_", n.ToString(),
".gif");
}

Save and Run. Do not forget to add these some style like these to
your page!

body
{
font: 11pt Calibri;
padding-top: 72px;
text-align: center
}
.text
{
font: 8pt Calibri
}
.div1
{
background-color: #ADD8E6;
}
.div2
{
background-color: #F0E68C;
}

Just by setting the Interval property of a Timer control to a small


value can generate significant traffic to the Web server. Take this
into consideration, and use the Timer control to refresh the content
only as often as necessary.

We moved our Web sites to Server Intellect and have found them to
be incredibly professional. Their setup is very easy and we were up
and running in no time.

This tutorial will demonstrate how to use the MutuallyExclusive


Checkbox Extender in ASP.NET AJAX C#

In this tutorial we will demonstrate how to enable the developer to


configure checkboxes that are mutually exclusive; which ensures
that the end-user will only be able to select a single option. This
control is similar in behavior to the radio-button list control. This
control is perfect for accepting only a specific confirmation from a
customer, such as yes/no to a newsletter or promotional email list.
Here is a snapshot of what this application will look like:

To start, open Visual Studio 2008. File > New > Web site > ASP.NET
Web Site and name it mutExChbx or whatever you want.

Checkboxes are usually used on the GUI and are Boolean in nature.
But sometimes there are Boolean conditions that are not so clear.
These could include a one-or-the-other value instead of just true or
false value.

Try Server Intellect for Windows Server Hosting. Quality and


Quantity!

Switch to Design View and insert the ToolkitScriptManager. Next


navigate on the top menu bar of VS2008 to table and select insert
table (2 x 1).

In this example, we will create an application that asks what is your


favorite color? We will set up Muttally exclusive checkboxes that ask
if Red, Yellow or Blue is your favorite color.

Back to the table. Locate the AJAX Toolkit that you installed and
double-click the ToolkitScriptManager with your cursor being above
the table.

Click on the top row and type “What is your favorite color?”
Then locate the checkboxes from the standard tab of the toolbox
and add three of them to the second row. Now navigate back to the
toolbox and go to the AJAX Toolkit tab and Drag over a
MutallyExclusiveCheckbox for each checkbox in the table. In the
Design View, it should look simialr to this:

Now we want to add values to the Checkboxes and labels to make


the form look exactly like what is shown above. Switch to Source
View. Your markup should look similar to this as well.

Add a text section to each checkbox and change some values to


make everything seem relevant.

<form id="myForm"
runat="server">
<div> </div>
<p style="text-align: center">
<asp:ToolkitScriptManager
ID="ToolkitScriptManager1"
runat="server">
</asp:ToolkitScriptManager>
</p> <table class="style1">
<tr>
<td> What is your Favorite Color?</td>
</tr>
<tr>
<td>
<asp:CheckBox
ID="Red"
runat="server"
Text="My Favorite Color is Red"/>
<asp:MutuallyExclusiveCheckBoxExtender
ID="RedColorExtender"
runat="server"
TargetControlID="Red"
Key="ColorChoice" />
<br />
<asp:CheckBox
ID="Yellow"
runat="server"
Text="My Favorite Color is Yellow" />
<asp:MutuallyExclusiveCheckBoxExtender
ID="YellowColorExtender"
runat="server"
TargetControlID="Yellow"
Key="ColorChoice" />
<br />
<asp:CheckBox
ID="Blue"
runat="server"
Text="My Favorite Color is Blue" />
<asp:MutuallyExclusiveCheckBoxExtender
ID="BlueColorExtender"
runat="server"
TargetControlID="Blue"
Key="ColorChoice" />
</td> /> </tr>
</table>
</form>

Notice how we added a Key value. The Key value is necessary


because we can define all the checkboxes to use the same key so
that the extenders can tell which other objec t that the
corresponding checkboxes should be mutually exclusive from.

If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

Save and Run.

Notice that when you choose one that you cannot choose another
one, thus they are mutually exclusive.

This tutorial will demonstrate how to use the Slider Control in an


ASP.NET 3.5 AJAX C#

In this tutorial we will show you how to simplify numeric user input
by using an AJAX control called the Slider control.

Here is a snapshot of the Web site:


To start, open Visual Studio 2008. File > New > Web Site > ASP.NET
Web Site and name it AJAXSliderCntrl or whatever you want.

Need help with Windows Dedicated Hosting? Try Server Intellect I'm
a happy customer!

Open the default.apsx page and add navigate to the AJAX


Extensions tab and double-click ScriptManger. Then below that add
two TextBox’s (Slider1, Slider1_BoundControl). The first TextBox
‘Slider1” will actually be the slider control. Then we want to
configure a bound control ‘Slider1_BoundControl’ that will be the
recipient of numeric value that is selected by the user by moving
the slider to different values.

Now navigate to the AJAX Library tab within the AJAX Toolkit that
you can download here and add a SliderExtender. Now we can
program the specific attributes that will be necessary to implement
the slider control with the behavior you want.

First specify the TargetControlID=”Slider1”, because we specified


the first TextBox the same name. Next specify the
BoundControlID=”Slider1_BoundControl” because that is what we
specified the second textbox. Now we want it to appear horizontally,
so specify the orientation=”horizontal”. Finally, set
EnableHandleAnimation = “true”. Here is the markup for the
SliderExtender:

<body>
<form id="myForm" runat="server">
<asp:ScriptManager
ID="ScriptManager1"
runat="server">
</asp:ScriptManager> <asp:TextBox
ID="Slider1"
runat="server">
</asp:TextBox> <asp:TextBox
ID="Slider1_BoundControl"
runat="server">
</asp:TextBox> <div> </div> >
<ajaxToolkit:SliderExtender
ID="SliderExtender1"
runat="server"
TargetControlID="Slider1"
BoundControlID="Slider1_BoundControl"
Orientation="Horizontal"
EnableHandleAnimation="true">
</ajaxToolkit:SliderExtender> </form>
</body>
</html>

It should look similar to this:

If you're ever in the market for some great Windows web hosting,
try Server Intellect.We have been very pleased with their services
and most importantly, technical support.
Next, let’s add some more advanced implementation. To begin,
grab two more TextBox’s and name them “Slider2” and
“Slider2_BoundControl”.

For Slider2, set Text=”0” and add AutoPostback=”true”, because


whenever the value changes we want to sutomatically do a
postback.

Below the Slider2_BoundControl add an UpdatePanel control. Then


add a ContentTemplate awithin the UpdatePanel. Then add a
Trigger’s collection as well with an <asp:ASyncpostBackTrigger>
with a ControlId=”Slider2” and add an EventName=”TextChanged”.
Remember that the SliderControlExtender extends a TextBox; so
when the value of that control changes, since the base object for
this control is a TextBox the value is changed.

Next let’s add to the ContentTemplate add a standard <asp:Label


and call it lblUpdateDate that will contain the updated time and
date.

Next, add the second <ajaxControlExtender for the slider. You can
just add the same attributes as for the slider control before. Make
sure you change all the names to the correct corresponding values.
Except this time change the Orientation attributes to “Vertical” and
add a Minimum value to”-99” and a maximum value to “99”.

<asp:TextBox
ID="Slider2"
AutoPostBack="true"
runat="server">
</asp:TextBox>
<asp:TextBox
ID="Slider2_BoundControl"
runat="server">
</asp:TextBox>
<asp:UpdatePanel
ID="UpdatePanel1"
runat="server">
<ContentTemplate>
<asp:Label
ID="lblUpdateDate"
runat="server" Text="">
</asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="Slider2"
EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>…..
<ajaxToolkit:SliderExtender
ID="SliderExtender2"
runat="server"
TargetControlID="Slider2"
BoundControlID="Slider2_BoundControl"
Orientation="Vertical"
Minimum="-99"
Maximum="99"
EnableHandleAnimation="true">
</ajaxToolkit:SliderExtender>

Now remember that we set up and UpdatePanel and specified that


the slider control trigger’s the EventName=”TextChanged” we want
to do a postback. In our Slider2 control we set AutoPostBack=”true”.
We want to update the text value within the label every time the
value for the Slider2 changes.

In order to achieve this functionality we need to generate a


Page_Load event for our page. This will be triggered when the
AutoPostBack happens. Enter some logic such as:

protected void Page_Load(object sender, EventArgs e)


{
ScriptManager1.RegisterAsyncPostBackControl(Slider2);
if (Page.IsPostBack)
{
lblUpdateDate.Text = "Changed at: " +
DateTime.Now.ToLongTimeString();
}
}

This code block above populates the lblUpdateDate with the current
time. Then RegisterAsyncPostBackControl registers Slider2.
Save and Run.

We moved our Web sites to Server Intellect and have found them to
be incredibly professional. Their setup is very easy and we were up
and running in no time.

This tutorial will show you how to add UpdatePanels within a


TabContainer using ASP.NET 3.5 AJAX C#.

In this tutorial we will demonstrate how to add two UpdatePanels


with two DropDownLists in each UpdatePanel and display two
seperate results within a TabContainer using ASP.NET 3.5 AJAX.

Here is a snapshot of what the final product looks like:

We moved our Web sites to Server Intellect and have found them to
be incredibly professional. Their setup is very easy and we were up
and running in no time.

To start, open Visual Studio 2008. File > New > Web Site > ASP.NET
Web Site and name it TabContainer or whatever you would like.

We will begin with adding a ToolkitScriptManager to the page in


design View by simply Double clicking it in the ASP.NET AJAX Library
or whatever you called it when you installed it into your toolbox. To
get the AJAX Toolkit just click here and follow the readme
instructions.

Then Let’s double-click on the TabContainer, located just under the


ToolkitScriptManager under the ASP.NET AJAX Library tab that we
just added. Then we need to add a TabPanel. Within the
<TabPanel> we need to add a <ContentTemplate>. Then within the
content template we need to add an <UpdatePanel>. Then add a
DropDownList and it should look similar to the code block below:

<body>
<form
id="myForm"
runat="server">
<ajaxToolkit:ToolkitScriptManager
ID="ToolkitScriptManager1"
runat="server">
</ajaxToolkit:ToolkitScriptManager>
<ajaxToolkit:TabContainer
ID="TabContainer1"
runat="server"
ActiveTabIndex="4">
<ajaxToolkit:TabPanel
ID="Zone1"
runat="server"
HeaderText="Zone 1">
<ContentTemplate>
<asp:UpdatePanel
ID="UpdatePanel1"
runat="server">
<ContentTemplate>
<fieldset>
<legend>Temperature</legend>
<asp:DropDownList
ID="ddlTemp"
runat="server"
DropDownControlID="Label1">
<asp:ListItem>90</asp:ListItem>
<asp:ListItem>85</asp:ListItem>
<asp:ListItem>80</asp:ListItem>
<asp:ListItem>75</asp:ListItem>
<asp:ListItem>70</asp:ListItem>
<asp:ListItem>65</asp:ListItem>
<asp:ListItem>60</asp:ListItem>
<asp:ListItem>55</asp:ListItem>
</asp:DropDownList>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>

We are creating a TabContainer with two UpdatePanels that are


independent of each other. We simply placed a DropDownList within
the UpdatePanel and made sure to use the correct syntax and
formatting <tags>. In this case we called the DropDownList
Temperature and filled it with some values.

Yes, it is possible to find a good web host. Sometimes it takes a


while. After trying several, we went with Server Intellect and have
been very happy. They are the most professional, customer service
friendly and technically knowledgeable host we've found so far.

Next we need to add a submit button so when the user chooses the
correct value from the DropDownList it is accepted and displayed
with a label within the UpdatePanel with a TimeStamp. It should look
similar to this:

<asp:Button
runat="server"
ID="btnUpdate"
Text="Update"
OnClick="btnUpdate_Click" />
</asp:button>
<asp:Label
ID="Label1"
runat="server"
ForeColor="green"
Font-Bold="true"
Font-Names="Courier New"
Font-Size="Large">
</asp:Label>

Of course, all the markup above is located in between


</asp:DropDownList> and </fieldset> tags.

Here is the code behind. The btnUpdate_Click event is called and


displays a message within that specific UpdatePanel with a
timeStamp to know when the temperature was changed.

protected void btnUpdate_Click(object sender, EventArgs j)


{
Label1.Text = "You selected: " +
ddlTemp.SelectedItem.Text + " was changed at " +
DateTime.Now.ToString();
}

This is a pretty cool feature with the AJAX Toolkit. Here are some
helpful hints in case you get lost in all the markup. Notice how the
TagPrefix=”ajaxToolkit” and also notice where and how the
TagPrefixes are used. You can also see where the TabContainer and
is located in the AJAX Toolkit.
If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome

This tutorial will demonstrate how to build tabbed content in an


ASP.NET 3.5 AJAX Web App C#

In this tutorial we will be using AJAX to build a tabbed content


browser. So when a user clicks a tab the AJAX will send and receive
the appropriate data for the corresponding tab. To begin, we will
start with a new ASP.NET Web Site. Open Visual Studio > File > New
> Web Site > ASP.NET and name it ajaxTabs or whatever you want.

Need help with Windows Dedicated Hosting? Try Server Intellect I'm
a happy customer!

We will need three IDs (one for container, one for content area, and
one for the loading status) with an ID class for the tabs.

<style type="text/css">
body
{
font-family: calibri;
font-size: 10px;
}
#container
{
width: 425px;
background-color: #52616F;
color: white;
}
.tabs
{
width: 50px;
margin-right: 10px;
padding: 4px;
text-align: center;
float: left;
cursor: pointer;
border: 1px solid #ccc;
border-bottom: 0;
}
#content
{
height: 350px;
clear: both;
border: 1px solid #ccc;
}
#load
{
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 20px;
background-color: red;
color: white;
display: none;
}
</style>

Above, the first ID #container will hold the tabs and the content
area. We will only give this a width which everything inside can
inherit from. The .tabs class is primarily for appearance and will
style our tabs.

Notice the property inside .tabs class is the .float:left and


cursor:pointer. The .float:left horizontally aligns the tabs and the
cursor:pointer allows the user to mouse over the tab to give it the
look and feel of a button.

Above, we also have the ID #content area which can be changed


depending on how much content you want. We also set the clear
property to clear:both because we have all the tabs floated left and
this makes the content div break into a new line just beneath.

The #load style is used for when AJAX communicates with the
server. We set the diplay to display:none so that it only shows when
the page is loading...

If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

Here is the XHTML that is needed for the styles above:


<body>
<center>
<div id="load"> Give it a Sec..</div>

<div id="container">
<div class="tabs" id="tab1"> Zone 1

<div class="tabs" id="tab2"> Zone 2

<div class="tabs" id="tab3"> Zone 3

<div class="tabs" id="tab4"> Zone 4

<div id="content">
</div>
</center>

The XHTML above should be straight-forward. We create the


container div with all the tab divs and the content div. Then we
apply the correct ID or class to the corresponding div.

Ok. The XHTML and CSS are complete. Now we will code a little
using JavaScript/Ajax.

Below the first function init(), which is attached to the body onload,
will set up the OnClick events for the tabs. Now we will recieve the
tabs as objects by using Prototype’s getElementsByClassName
function. This returns an array of all elements with the class name
provided as a parameter. Then we need to loop through the array
and add an OnClick function.

Now set up the tabs so when are clicked they trigger getTabData
and pass it the tab ID so that the server side can figure out which
data to pass back to the content area. We set the URL which is what
will determine what data to pass back, and we also created a new
variable called rand. That variable ensures the content is NEVER
cached on the server side.

<script type="text/javascript">
function init()
{
var tabs = document.getElementsByClassName('tabs');
for (var i = 0; i < tabs.length; i++)
{
$(tabs[i].id).onclick = function()
{
getTabData(this.id);
}
}
}
function getTabData(id)
{
var url = 'demos/ajax-tabs/process.php';
var rand = Math.random(9999);
var pars = 'id=' + id + '&rand=' + rand;
var myAjax = new Ajax.Request(url, { method: 'get',
parameters: pars, onLoading: showLoad, onComplete:
showResponse });
}
function showLoad()
{
$('load').style.display = 'block';
}
function showResponse(originalRequest)
{
var newData = originalRequest.responseText;
$('load').style.display = 'none';
$('content').innerHTML = newData;
}
init();
</script>

Now we need to create our parameters variables to tell the Ajax


object what parameters we will pass to the server side. Then we
create an AJAX object, set the method to get, pass in the
parameters and set our event functions for the object.

The showLoad function changes the CSS style of the load div to
block, ($('load').style.display = 'block';), which notifies the user that
the content is loading…

We chose Server Intellect for its dedicated servers, for our web
hosting. They have managed to handle virtually everything for us,
from start to finish. And their customer service is stellar.
The showResponse function has a parameter of original Request
(the data that is passed back from the server). Within this function
we set the load div back to display:none and then populate the
content div with the correct data that we get from the server.

This tutorial will demonstrate how to DataBind to an Accordion using


the ASP.NET 3.5 AJAX control toolkit.

In this tutorial we explore the accordion control in the AJAX Control


Toolkit. The AJAX Toolkit provides multiple pane sand allows the
user to display one of them at a time. Usually, panels are declared
within the page itself, but binding them to a data source offers more
flexibility.

Here is a great place to download the AJAX Toolkit Ajax ToolKit

To begin, a DataSource is required. For this example, we will use an


instance of SQL Server 2008.

To activate the functionality of the ASP.NET AJAX and the Control


Toolkit, the Scriptmanager must be placed on the page.

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

If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

Configuring a DataSource

Next we need to add a data source onto the page. Assuming that
you already have created a DataSource locate the Server Explorer.
Right-click Data Connections > Add Contection then the dialog box
appears.
If the Data source does not display SQL Server(SqlClient) click
Change and within Change Data Source dialog box, select SQL
Server.
If the Choose Data Source page appears, within the Data source list,
select the type of data source that you’ll be using.
If the Server Explorer is not visible, you can locate it in the View Tab
of Visual Studio’s Toolbar. The same goes for the Database Explorer.
In the Add Connection box, enter the name of the server name
within the Server name box. In the Log on to theserver section,
select the option that is appropriate to access the running SQL
Server Database and, if required, enter a user naem and password.
Select save my password in the check box if you entered a
password.
Yes, it is possible to find a good web host. Sometimes it takes a
while. After trying several, we went with Server Intellect and have
been very happy. They are the most professional, customer service
friendly and technically knowledgeable host we've found so far.
Next under Select or enter database name, enter or select the
corresponding database. Test Connection.
Now let's get started. Select and drag the table you wish to use onto
the blank page (design view) under the ScriptManager.

Remember the name (ID) for the data source. It will be used in the
DataSourceID property for the Accordion control like this example:
<ajaxToolkit:Accordion
ID="accordion1"
runat="server"
HeaderCssClass="header"
ContentCssClass="content"
Width="300px"
DataSourceID="SqlDataSource1"
FadeTransitions="true">
Within the Accordion control, you can provide templates for various
parts of the control, including the header(<HeaderTemplate>) and
the content(<ContentTemplate>). Within these elements, using the
DataBinder.Eval() method to output the data from the data source.
<HeaderTemplate>ID
<%#DataBinder.Eval(Container.DataItem, "ID")%>
</HeaderTemplate>
<ContentTemplate>
<%#DataBinder.Eval(Container.DataItem, "Name")%>
</ContentTemplate>
</ajaxToolkit:Accordion>
Now enter this server-side code so that when the page is loaded the
data source is bound to the accordion:
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.DataBind();
}
**Do not Forget! Inlcude these two CSS classes that are referenced
in the Accordion control; in its properties HeaderCssClass and
ContentCssClass. Place this markup in the head section of your
default.aspx:
<style type="text/css">
.header {background-color: blue;}
.content {border: solid;}
</style>

We migrated our web sites to Server Intellect over one weekend and
the setup was so smooth that we were up and running right away.
They assisted us with everything we needed to do for all of our
applications. With Server Intellect's help, we were able to avoid any
headaches!

In part 1 of 3, of this tutorial we will learn how an ASP.NET AJAX Web


Service handler is configured, how a Web Service request message
is serialized to JSON, how to create AJAX-enabled Web Services
and how to use the ScriptService and ScriptMethod attribute.

In this tutorial we will explore how Web services are an essential


part of the .NET Framework for providing cross-platform solutions
for exchanging data between distributed systems. Instead of
resorting to postback operations, the Web services are used to
dynamically inject data into an ASP.NET AJAX page or send data
from a page to a back-end system.

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

Within the ASP.NET AJAX Toolkit there is functionality available


through ASP.NET AJAX Extensions as well as a Web service control
called AutoCompleteExtender that we will focus on in this tutorial.

The web.config file has a number of new additions that you may be
unfamiliar with in Visual Studio 2008. Certain map the <asp> prefix
to ASP.NET AJAX controls so that they can be used in pages while
others define required <HttpHandlers> and <HttpModules>. The
default HttpHandler used to process .asmx (Active Server Methods)
calls is removed and replaced with a ScriptHandlerFactory class
located in System.Web.Extensions.dll assembly, which contains all
the core functionality used by ASP.NET AJAX.

This is an ASP.NET AJAX Web Service Handler


Configuration

<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false"

type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=1.0.61025.0,
Culture=neutral, PublicKeyToken=63nk5335ji533l53"/>
</httpHandlers>
This httpHandler replacement is made in order to allow JavaScript
Object Notation (JSON) calls to be made from ASP.NET AJAX pages to
.NET Web services using a JavaScript Web Service Proxy. Instead of
using the SOAP protocol, ASP.NET AJAX sends JSON messages to
Web services that results in smaller request and response messages
overall. This is more efficient client-side processing of data due to
ASP.NET AJAX JavaScript library which is optimized to work with
JSON objects.
If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

Learn How a Web Service Request Message Serialized


to JSON

{"university":"Calculus"}

Learn How a Web Service Response Message


Serialized to JSON

[{"__type":"Model.Student","University":"Calculus","SchoolN
ame": "University
Name","StudentID":"FLASD","ContactName":"SomeName"},
{"__type":"Model.Student","University":"Calculus","SchoolN
ame": "University
Name","StudentID":"SUTRD","ContactName":"SomeName"}]

Above is an example of a Web service request and response


messages serialized to JSON format. In the first case University
passes a class parameter with a value of “Calculus”. In the second
block an array of Student objects and their properties.

Learn How to Create AJAX-Enabled Web Services


There are several ways to call Web services within ASP.NET AJAX
framework. There is either the AutoCompleteExtender in the Toolkit
or using JavaScript. It is pretty straight forward in creating AJAX-
enabled services because .Net framework has supported Web
services since 2002 and the ASP.NET AJAX Extensions has been built
upon. Below is an example of using WebMethod attribute in a Web
service:
public Student[] GetStudentsByUniversity(string university)
{
return Biz.BAL. GetStudentsByUniversity(university);
}

As shown above the GetStudentsByCountry() method accepts a


university parameter and returns a Student object array. The
university value passed into the method is forwarded to a business
layer class which in turn calls a data layer class to retrieve the data
from the database, then fills the Student object properties with data
and returns the array.
We migrated our web sites to Server Intellect over one weekend and
the setup was so smooth that we were up and running right away.
They assisted us with everything we needed to do for all of our
applications. With Server Intellect's help, we were able to avoid any
headaches!

Learn How to Use the ScriptService Atrribute

When adding the WebMethod attribute it allows the


GetStudentsByUnivserity() method to be called by clients that send
standard SOAP messages to the Web Service. This doesn’t allow the
JSON calls to be made from the default setting in ASP.NET AJAX
applications. Instead, to allow the JSON calls to be made you will
need to apply the ASP.NET AJAX Extension’s ScriptService attribute
to the Web service class. By doing this it enables a Web service to
send a response message forward using JSON and also allows the
client-side script to call a service by sending JSON messages. Below
is an example of a service class called StudentsService that apply’s
the ScriptService attribute.
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://xmlforasp.net")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]
public class StudentsService :
System.Web.Services.WebService
{
[WebMethod]
public Student[] GetStudentsByUniversity(string university)
{
return Biz.BAL.GetStudentsByUniversity(university);
}
}
Learn How to Use the ScriptMethod Attribute

The only ASP.NET AJAX attribute that has to be defined in a .NET


Web service is the ScriptService attribute in order for it to be used
by ASP.NET AJAX pages. Although a ScriptMethod attribute can be
applied directly to Web method in a service. A ScriptMethod defines
three properties; UseHttpGet, ResponseFormat, XmlSerializeString.
Using the ScriptMethod attribute with the UseHttpGet property can
be used to accept GET request instead of POST requests. These
requests are sent using a URL with Web Method input parameters
converted to QueryString parameters. Here is an example:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string HttpGetEcho(string input)
{
return input;
}

Ok, we know now that the Web Methods can accept HTTP GET
requests. Additionally, the ScriptMethod attribute can be used when
XML responses need to be returned from a service rather than JSON.
Let’s say, a Web Service retrieves an RSS Feed from a remote site
and returns it as an XMLDocument or XMLElement object, then the
processin gfo the XML data can then occur on the client. Below
illustrates using the ResponseFormat property to specify that XML
data should be returned from a web Method.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XmlElement GetRssFeed(string url)
{
XmlDocument doc = new XmlDocument();
doc.Load(url);
return doc.DocumentElement;
}

We moved our Web sites to Server Intellect and have found them to
be incredibly professional. Their setup is very easy and we were up
and running in no time.
The ResponseFormat property can also be used with the
XMLSerializeString property which has a default value of false and
can return all types except for strings. Strings that are returned
from a Web method are serialized as XML when the
ResponseFormat property is set to responseFormat.XML. However,
when the XMLSerializeString is set to true, every type return from
the Web Method is serialized as XML. Here is an example of an
XMLSerializeString property to force strings to be serialized as XML.
[WebMethod]
[ScriptMethod(ResponseFormat =
ResponseFormat.Xml,XmlSerializeString=true)]
public string GetXmlString(string input)
{
return input;
}

Here is an example of the value returned from calling the


GetXmlStrng Web Method:
<?xml version="1.0"?> <string>Test</string>
Coming up in part 2 of 3 of this tutorial: We will learn how to work
with complex types, create and use JavaScript proxies, handle errors
and XML data returned from ASP.NET AJAX Web Services.

This tutorial will show you how to create and implement an AJAX-
enabled WCF Service into an ASP.NET Web page. WCF (or Windows
Communication Foundation) is a union of technologies developed by
Microsoft to make it easier and quicker for developers to build
distributed applications.

We are going to create a single web page that will allow the input of
two numbers from the user, then we will access a WCF Service to
make a calculation and return the value back to the Web Page. We
will do this using AJAX so that we will get a near-instant response.

To start, create a new Web Application in Visual Studio 2008, and


then in Solution Explorer, right-click the Project, choose Add New
Item.. AJAX-enabled WCF Service. Name it Service1.svc - you will
see that it is added to the Solution Explorer, along with a
Service1.cs in the App_Code folder. The .cs file should open upon
creation, and look something like this:

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
// Add [WebGet] attribute to use HTTP GET
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}

// Add more operations here and mark them with


[OperationContract]
}

We used over 10 web hosting companies before we found Server


Intellect. Their dedicated servers and add-ons were setup swiftly, in
less than 24 hours. We were able to confirm our order over the
phone. They respond to our inquiries within an hour. Server
Intellect's customer support and assistance are the best we've ever
experienced.

This is where we will add our logic to perform the calculation We will
add a method to add two numbers together, like so:

[OperationContract]
public Double Add(Double theNum1, Double theNum2)
{
return theNum1 + theNum2;
}

If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

Notice we specify a static method, and the OperationContract


attribute defines it as an operation of this Service.
Now if we move to our ASPX page, we will want to add a
ScriptManager to the page to manage all of our AJAX calls behind
the scenes. But in order for our Service method to be accessible at
page level, we will need to add a Service reference to our WCF
Service. We do so like this:

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


<Services>
<asp:ServiceReference Path="~/Service1.svc" />
</Services>
</asp:ScriptManager>

Now let's go ahead and create our form. We will use HTML form
elements, as we are going to use JavaScript to call our Service
method.

<input type="text" id="num1" size="3" /> + <input


type="text" id="num2" size="3" /><br />
<input type="button" id="jsSubmit" value="Submit"
onclick="AddNumbers()" />
Try Server Intellect for Windows Server Hosting. Quality and
Quantity!

Nothing much different to a regular ASP.NET Web Application here.


Notice we include the handler for the button. Here we are calling a
JavaScript function, which we can now add to the page. Add the
following to the bottom of the page:

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


function AddNumbers() {
Service1.Add(document.getElementById('num1').valu
e, document.getElementById('num2').value,
onSuccess);
}

function onSuccess(string) {
alert('Answer = ' + string);
}
</script>

Here, we are directly referencing the public method we created


within the WCF Service. We have access to this via JavaScript
because we are using the ScriptManager to expose the Service to
page level. We get the response from the method and display it in a
JavaScript alert window. We have no need to write any code-behind
logic, as all of the functionality is being handled by the Service. We
can expand this Web Application by creating more methods
(Operation Contracts) in the Service, and then referencing them in
the same way via JavaScript.
Our entire Service code looks like this:

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
// Add [WebGet] attribute to use HTTP GET
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}

// Add more operations here and mark them with


[OperationContract]
[OperationContract]
public Double Add(Double theNum1, Double theNum2)
{
return theNum1 + theNum2;
}
}

We moved our web sites to Server Intellect and have found them to
be incredibly professional. Their setup is very easy and we were up
and running in no time.

Our ASPX page will look something like this:

<html>
..
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
<Services>
<asp:ServiceReference Path="~/Service1.svc" />
</Services>
</asp:ScriptManager>

<input type="text" id="num1" size="3" /> + <input


type="text" id="num2" size="3" /><br />
<input type="button" id="jsSubmit" value="Submit"
onclick="AddNumbers()" />
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
function AddNumbers() {
Service1.Add(document.getElementById('num1').valu
e, document.getElementById('num2').value,
onSuccess);
}

function onSuccess(string) {
alert('Answer = ' + string);
}
</script>

In this tutorial, you will learn how to cancel an Asynchronous


PostBack that is currently in progress. This is useful when a user has
submitted a request to a web page that uses AJAX, and they can see
that their request is pending - through the use of an
UpdateProgress, for example - and they decide they want to cancel
that request for whatever reason. We can make this a reality for
users with a little JavaScript.

For this example, we will create one main UpdatePanel and then a
nested UpdatePanel and an UpdateProgress. We should have
something like this:

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server">


<ContentTemplate>
<asp:UpdatePanel ID="UP2" runat="server">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>

<asp:UpdateProgress ID="UPr1" runat="server"


AssociatedUpdatePanelID="UP2">
<ProgressTemplate>

</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
</form>

We moved our web sites to Server Intellect and have found them to
be incredibly professional. Their setup is very easy and we were up
and running in no time.

Now we will place a Literal in the second UpdatePanel, and also a


Button:

<asp:UpdatePanel ID="UP2" runat="server">


<ContentTemplate>
<asp:Literal ID="lit_DateTime" runat="server" />
<br />
<asp:Button ID="btn_GetTime" runat="server"
Text="Get Current Time"
OnClick="btn_GetTime_Click" />
</ContentTemplate>
</asp:UpdatePanel>

Notice here that we add a handler to the Button Click event. We will
also set the Date and Time on Page_Load, but only the first time it
loads - not on PostBacks. The code-behind will look something like
this:
using System;

using System.Threading;

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


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lit_DateTime.Text = DateTime.Now.ToString();
}
}

protected void btn_GetTime_Click(object sender,


EventArgs e)
{
Thread.Sleep(3000);
lit_DateTime.Text = DateTime.Now.ToString();
}
}

If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

On load and on button click we are simply displaying the current


date and time in the Literal control. Also on the button click, we are
putting it to sleep first, for 3 seconds, which will give us a chance to
cancel the process before it's complete.

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginR
equest(startRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRe
quest(endRequest);

function startRequest(sender, e) {
//disable button during the AJAX call
document.getElementById('<%=btn_GetTime.ClientID
%>').disabled = true;
document.getElementById('<%=btn_GetTime.ClientID
%>').value = 'Getting time..';
}
function endRequest(sender, e) {
//re-enable button once the AJAX call has completed
document.getElementById('<%=btn_GetTime.ClientID
%>').disabled = false;
document.getElementById('<%=btn_GetTime.ClientID
%>').value = 'Get Current Time';
}
</script>
Try Server Intellect for Windows Server Hosting. Quality and
Quantity!

Now all that is left to do is to add the JavaScript to handle the


cancellation of the Async PostBack. It is important to note that this
method will not actually stop the Server from processing the
request; it will only cause the Page Request Manager to ignore the
response from the Server. With this in mind, if the Server is
performing a lengthy process, it may be worth making a new Async
call to explicitly halt that activity.

Add the following script to the bottom of the page. This will check to
see if the Cancel button is the one making the call, and if so, will
abort the pending PostBack.

<script type="text/javascript">
var instance =
Sys.WebForms.PageRequestManager.getInstance();
instance.add_initializeRequest(instance_initializeRequest
);

function instance_initializeRequest(sender, args) {


if (args.get_postBackElement().id == 'btn_Cancel') {
instance.abortPostBack();
alert('Postback has been cancelled. Time will not
be updated.');
}
}
</script>

In this tutorial, we will be looking at how to use AJAX to make


Asynchronous calls, and also how to manage those calls by disabling
our button until the call completes. Often, if a user doesn't see near-
immediate results when they make a request (click a button for
example), that user will try to make the call again. This can cause
problems, especially when using AJAX as the last call made will take
precendence over any that are currently in progress. A good way to
deal with this is to give the user visual feedback that their request is
processing. This can be done with an UpdateProgress control, for
example. But another way to do it is to disable the button whilst an
Asynchronous request is being processed.

To demonstrate how to do this, we will create a small form with an


UpdatePanel and a Button. The button will get the current time on
the server, which will take only milliseconds to complete - too fast
for us to demonstrate the button being disabled. For this example,
we will slow the request down by making it sleep for 2 seconds
before processing.
We start by building out our ASPX page. Let's add a ScriptManager
and an UpdatePanel:

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server">


<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>
<br />
</form>

We are using Server Intellect and have found that by far, they are
the most friendly, responsive, and knowledgeable support team
we've ever dealt with!

In our UpdatePanel, we are going to output the current Date and


Time, and also include a Button to allow the user to update it:

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server">


<ContentTemplate>
<%= DateTime.Now.ToString() %>
<br />
<asp:Button ID="btn_GetTime" runat="server"
Text="Get Current Time"
OnClick="btn_GetTime_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
</form>

Notice we have a handler for the Button's click event. This is where
we are going to slow the process down. In the code-behind, we will
add the following:

using System.Threading;

..

protected void btn_GetTime_Click(object sender, EventArgs


e)
{
Thread.Sleep(3000);
}
If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

All that is left to do is to disable the button during the Async


PostBack. We will do this using JavaScript, as it will be executed in
the browser and will be effective immediately. At the bottom of the
page, we add the following script:

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginR
equest(startRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRe
quest(endRequest);

function startRequest(sender, e) {
//disable button during the AJAX call
document.getElementById('<%=btn_GetTime.ClientID
%>').disabled = true;
document.getElementById('<%=btn_GetTime.ClientID
%>').value = 'Getting time..';
}
function endRequest(sender, e) {
//re-enable button once the AJAX call has completed
document.getElementById('<%=btn_GetTime.ClientID
%>').disabled = false;
document.getElementById('<%=btn_GetTime.ClientID
%>').value = 'Get Current Time';
}
</script>

Here, we are calling a function on the start of an Async Request, and


then another method on the end of the Request. These functions
change the disabled value of the button, and also the text. Now
when we run this application, we will be able to click the button to
retrieve the current date and time, and display it to the page. We
are also pausing the request for two seconds, so that we can see
during the request that the button is disabled and the text is
temporarily changed. When the request is complete, however, we
re-enable the button and change the text back.

<script type="text/javascript">
var instance =
Sys.WebForms.PageRequestManager.getInstance();
instance.add_initializeRequest(instance_initializeRequest
);

function instance_initializeRequest(sender, args) {


if (instance.get_isInAsyncPostBack()) {
alert('Still processing request. Please wait..');
args.set_cancel(true);
}
}
</script>

We moved our web sites to Server Intellect and have found them to
be incredibly professional. Their setup is very easy and we were up
and running in no time.

The ASPX will look something like this:

<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="SM1" runat="server" />

<asp:UpdatePanel ID="UP1" runat="server">


<ContentTemplate>
<%= DateTime.Now.ToString() %>
<br />
<asp:Button ID="btn_GetTime" runat="server"
Text="Get Current Time"
OnClick="btn_GetTime_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
</form>
</body>
</html>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginR
equest(startRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRe
quest(endRequest);

function startRequest(sender, e) {
//disable button during the AJAX call
document.getElementById('<%=btn_GetTime.ClientID
%>').disabled = true;
document.getElementById('<%=btn_GetTime.ClientID
%>').value = 'Getting time..';
}
function endRequest(sender, e) {
//re-enable button once the AJAX call has completed
document.getElementById('<%=btn_GetTime.ClientID
%>').disabled = false;
document.getElementById('<%=btn_GetTime.ClientID
%>').value = 'Get Current Time';
}
</script>

AJAX brings a lot of functionality to Web Applications, and an almost


desktop-like experience. Users no longer have to wait for the whole
page to be resent from the Web Server when making a small
request on the page. AJAX has the ability to update areas of a page
separately using UpdatePanels. However, when there are multiple
UpdatePanels on a page, the user may mistakingly begin another
Asynchronous Request while one is being processed. For example, if
a user makes one change on the web page and the process is still
active when they make another AJAX request, the second request
will take precedence over the first. This means the first request will
never complete.

In this tutorial, you will learn how to use AJAX to detect if an


Asynchronous request is still being processed when another is
called. By doing this, we can notify the user, and allow the first
request to complete before starting another.
To demonstrate this, we will create two UpdatePanels, each
displaying the current date and time, and with a button. Each button
will update its own UpdatePanel when clicked. However, when the
first button is clicked, we will purposely make the process take 3
seconds to complete, giving us enough time to click the second
button to test. Upon clicking the second button while the first is still
processing, we should be notified that a process is still active and
not allow the second process to initiate.

Let's start by adding the ScriptManager and the two UpdatePanels:

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server"


UpdateMode="Conditional">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>

<br /><br />


<asp:UpdatePanel ID="U2" runat="server"
UpdateMode="Conditional">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>
<br /><br />
</form>

Notice we set the UpdateMode on both Panels to Conditional. This is


because we do not want them both updating at the same time -
each button should update their own UpdatePanel only.
Let's go ahead and add the buttons and the current time to the
UpdatePanels:
<asp:UpdatePanel ID="UP1" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<%= DateTime.Now.ToString() %>
<br />
<asp:Button ID="btn_GetTime1" runat="server"
Text="Get Time (1)" OnClick="btn_GetTime1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<br /><br /> <asp:UpdatePanel ID="U2" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<%= DateTime.Now.ToString() %>
<br />
<asp:Button ID="btn_GetTime2" runat="server"
Text="Get Time (2)" />
</ContentTemplate>
</asp:UpdatePanel>

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

Notice we include a handler for the first Button - here we will make
the thread sleep for 3 seconds. This will be done in the code-behind
like so:

using System.Threading;

..

protected void btn_GetTime1_Click(object sender, EventArgs


e)
{
Thread.Sleep(3000);
}

To make the request more visual, let's add an UpdateProgress into


the mix as well. This will show us when a request is in progress:

<asp:UpdateProgress ID="UPr1" runat="server"


AssociatedUpdatePanelID="UP1">
<ProgressTemplate>
<br /><br />
Please wait..
</ProgressTemplate>
</asp:UpdateProgress>

Server Intellect assists companies of all sizes with their hosting


needs by offering fully configured server solutions coupled with
proactive server management services. Server Intellect specializes
in providing complete internet-ready server solutions backed by
their expert 24/365 proactive support team.
We will also include some JavaScript to check if an Async PostBack is
currently in progress. To do this, add the following script:

<script type="text/javascript">
var instance =
Sys.WebForms.PageRequestManager.getInstance();
instance.add_initializeRequest(instance_initializeRequest
);

function instance_initializeRequest(sender, args) {


if (instance.get_isInAsyncPostBack()) {
alert('Still processing request. Please wait..');
args.set_cancel(true);
}
}
</script>

If you're ever in the market for some great Windows web hosting,
try Server Intellect. We have been very pleased with their services
and most importantly, technical support.

Now when we push the first button, it will wait for 3 seconds before
updating the time. If you push the second button before the time
updates, we will get a popup message notifying us that the request
is still processing.
The ASPX page will look something like this:

<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="SM1" runat="server" />

<asp:UpdatePanel ID="UP1" runat="server"


UpdateMode="Conditional">
<ContentTemplate>
<%= DateTime.Now.ToString() %>
<br />
<asp:Button ID="btn_GetTime1" runat="server"
Text="Get Time (1)" OnClick="btn_GetTime1_Click"
/>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UPr1" runat="server"
AssociatedUpdatePanelID="UP1">
<ProgressTemplate>
<br /><br />
Please wait..
</ProgressTemplate>
</asp:UpdateProgress>
<br /><br />
<asp:UpdatePanel ID="U2" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<%= DateTime.Now.ToString() %>
<br />
<asp:Button ID="btn_GetTime2" runat="server"
Text="Get Time (2)" />
</ContentTemplate>
</asp:UpdatePanel>
<br /><br />
</form>
</body>
</html>
<script type="text/javascript">
var instance =
Sys.WebForms.PageRequestManager.getInstance();
instance.add_initializeRequest(instance_initializeRequest
);

function instance_initializeRequest(sender, args) {


if (instance.get_isInAsyncPostBack()) {
alert('Still processing request. Please wait..');
args.set_cancel(true);
}
}
</script>

In this tutorial, we will be looking at the Modal Popup Extender in


the AJAX Control Toolkit from Microsoft. The aim of the Control
Toolkit is to make it easier for developers to implement AJAX
functionality into Web Applications. It is made even easier in
ASP.NET 3.5 as AJAX comes built-in. This tutorial is written with and
aimed at ASP.NET 3.5, as it ships with native AJAX support.
However, if you're using ASP.NET version 2.0, you can still make use
of AJAX by downloading and installing the AJAX Extensions from this
page.

The AJAX Control Toolkit is an add-on for ASP.NET that can be


downloaded from Microsoft's Codeplex. Upon visiting this page, you
will notice that you have the choice of downloading the source code
for all Controls and Extenders, or just the compiled DLL. Unless you
plan on modifying the existing controls, you should get the DLL or
NoSource. We would recommend getting the NoSource version, as it
comes with the sample site which demonstrates how each of the
new Controls and Extenders work.

Download and extract the ZIP file to somewhere on your computer,


make note of where. You will notice in the ZIP archive that there is
DLL: AjaxControlToolkit.dll; this is what we want. Open up Visual
Studio and create a new Web Application project. Open up the
toolbox panel (View > Toolbox) and right-click in an empty space,
then choose Add Tab. Enter a descriptive name like AJAX Toolkit and
press Enter. Now right-click in an empty space beneath this new tab
and click Choose Items, and on the .NET Framework Components
tab click the Browse button and navigate to the dll we just
downloaded. Once chosen, click Ok to return to Visual Studio. You
should see that all Toolkit controls and extenders have been added
to the tab we created.
In this tutorial, we are going to look more closely at the Modal Popup
Extender. We will be creating a button that will cause the popup,
and then within the popup, we will display a Repeater control to
demonstrate how we can have functionality and data within a
popup.

The first thing we do is to create a textbox and a button. We will be


using the textbox to display data back to the user, in this example.
Because the popup will use JavaScript, the easiest way to pass back
the information will be via a JavaScript function, and a textbox is
easiest to assign from JavaScript:

<form id="form1" runat="server">


<asp:TextBox ID="lit_Status" runat="server"
Enabled="false" CssClass="txtBox"
BorderColor="White" /><br />
<asp:Button ID="btn_Submit" runat="server"
Text="Click to Popup" />
</form>

Need help with Windows Dedicated Hosting? Try Server Intellect. I'm
a happy customer!

Notice here we are disabling the textbox, and also hiding the
border. We created a CSS class for it:

.txtBox
{
border:none;
}

The Modal Popup extender uses an ASP.NET Panel control, which


opens up within the browser. Our next step is to create that Panel,
and for this example, we will include a Repeater within to
demonstrate our ability to display dynamic data within a popup, and
not just static text. We will also add an Ok and a Cancel button, and
demonstrate how we can pass values back from the Popup using
JavaScript:

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


CssClass="ModalPopup" Width="500" Height="350">
<br />Hello World<br />
<br />
This is a Repeater:<br />
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate><table
width="450"><tr><th>Name</th><th>Age</th><th>Cit
y</th></tr></HeaderTemplate>
<ItemTemplate>
<tr><td><%# Eval("Name") %></td>
<td><%# Eval("Age") %></td>
<td><%# Eval("City") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:Button ID="btn_Ok" runat="server" Text="OK" />
<asp:Button ID="btn_Cancel" runat="server"
Text="Cancel" />
</asp:Panel>

Server Intellect assists companies of all sizes with their hosting


needs by offering fully configured server solutions coupled with
proactive server management services. Server Intellect specializes
in providing complete internet-ready server solutions backed by
their expert 24/365 proactive support team.

In our simple Repeater, we are going to display columns Name, Age


and City. Using this structure, we will programmatically create a
DataTable on Page_Load and then assign that to the Repeater, like
so:

protected void Page_Load(object sender, EventArgs e)


{
DataTable dt = new DataTable();
DataColumn dc;

dc = new DataColumn();
dc.ColumnName = "Name";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "Age";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "City";
dt.Columns.Add(dc);

DataRow dr;
dr = dt.NewRow();
dr["Name"] = "Mikel";
dr["Age"] = "19";
dr["City"] = "London";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Ryan";
dr["Age"] = "47";
dr["City"] = "Glendale";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Sheila";
dr["Age"] = "30";
dr["City"] = "Miami";
dt.Rows.Add(dr);

Repeater1.DataSource = dt;
Repeater1.DataBind();
}

This will be the only code we write, because the Modal Popup
Extender is pre-built: all there is to do is to pop it in from the toolbox
and configure it. So let's go ahead and do that - drag the
ModalPopupExtender from the AJAX Toolkit in the Toolbox, then add
the following attributes:

<asp:Button ID="btn_Submit" runat="server" Text="Click to


Popup" />
<cc1:ModalPopupExtender ID="ModalPopupExtender1"
runat="server" BackgroundCssClass="Inactive"
OkControlID="btn_Ok"
TargetControlID="btn_Submit"
CancelControlID="btn_Cancel"
OnCancelScript="onCancel()" OnOkScript="onOk()"
PopupControlID="panel_Popup" />

We are using Server Intellect and have found that by far, they are
the most friendly, responsive, and knowledgeable support team
we've ever dealt with!

We set the TargetControlID as the button that will cause the popup,
the OkControlID and the CancelControlID reference the buttons
within the Panel to let the extender know which controls handle
these tasks. We also create another CSS style for the background
when the popup is open, and finally, we call JavaScript functions on
Ok and on Cancel. First, the CSS classes looks like this

.Inactive
{
background-image: url('media/inactive-bg.gif');
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
.ModalPopup
{
background-color:transparent;
background: url('media/popup-bg.gif') no-repeat;
background-position:center;
padding:0;
border: none;
}

Next, the JavaScript functions look like this (we put these at the
bottom of the page)::

<script type="text/javascript">
function onOk() {
document.getElementById('<%=lit_Status.ClientID
%>').value = 'You clicked Ok.';
}
function onCancel() {
document.getElementById('<%=lit_Status.ClientID
%>').value = 'You clicked Cancel.';
}
</script>

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

Now that everything is in place, we can run this and notice that
when the button is clicked, the Popup shows instantly. Then we can
close the panel with either Ok or Cancel - and the results of which
button you clicked will be displayed on the page. Notice also that
the Repeater displays the data within the panel, even though we're
binding it on Page_Load. The ASPX page will looks something like
this:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Using AJAX Control Toolkit for Modal Popup in
ASP.NET 3.5 and C#</title>
<style>
<!--
.Inactive
{
background-image: url('media/inactive-bg.gif');
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
.ModalPopup
{
background-color:transparent;
background: url('media/popup-bg.gif') no-repeat;
background-position:center;
padding:0;
border: none;
}
.txtBox
{
border:none;
}
-->
</style>
</head>

<body>
<form id="form1" runat="server">
<asp:TextBox ID="lit_Status" runat="server" Enabled="false"
CssClass="txtBox" BorderColor="White" /><br />
<asp:Button ID="btn_Submit" runat="server" Text="Click to
Popup" />
<cc1:ModalPopupExtender ID="ModalPopupExtender1"
runat="server" BackgroundCssClass="Inactive"
OkControlID="btn_Ok"
TargetControlID="btn_Submit"
CancelControlID="btn_Cancel"
OnCancelScript="onCancel()" OnOkScript="onOk()"
PopupControlID="panel_Popup" />

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


CssClass="ModalPopup" Width="500" Height="350">
<br />Hello World<br />
<br />
This is a Repeater:<br />
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate><table
width="450"><tr><th>Name</th><th>Age</th><th>
City</th></tr></HeaderTemplate>
<ItemTemplate>
<tr><td><%# Eval("Name") %></td>
<td><%# Eval("Age") %></td>
<td><%# Eval("City") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:Button ID="btn_Ok" runat="server" Text="OK" />
<asp:Button ID="btn_Cancel" runat="server"
Text="Cancel" />
</asp:Panel>
</form>
</body>
</html>
<script type="text/javascript">
function onOk() {
document.getElementById('<%=lit_Status.ClientID
%>').value = 'You clicked Ok.';
}
function onCancel() {
document.getElementById('<%=lit_Status.ClientID
%>').value = 'You clicked Cancel.';
}
</script>

Using Repeater to Edit in-line with AJAX in VB.NET

In this tutorial, we will be looking at how we can replicate the built-in


feature of the GridView control and use a Repeater to edit data
inline and almost without delay. We will be using AJAX to call
asynchronous postbacks, and allow editing of data a row at a time.

This tutorial was written with ASP.NET 3.5 using Visual Studio 2008.
If you are using 2005 with ASP.NET 2.0, then you will need to
download the AJAX Extensions from Microsoft.

The first thing we will do is to add the ScriptManager to our ASPX


page, which will manage all of our AJAX calls:

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

Next, we can add an UpdatePanel to the page:

<asp:UpdatePanel ID="UP1" runat="server"


RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>

</HeaderTemplate>
<ItemTemplate>

</ItemTemplate>
<FooterTemplate>

</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

We will make use of the Header template to start a HTML table, and
the Footer template to end it. The Content template will be used for
the data we will be displaying. For this example, we will display data
from an XML file. The XML will look something like this:
<?xml version="1.0" encoding="utf-8" ?>

<People>
<Person>
<ID>1</ID>
<Name>Freddie Cosgrove</Name>
<Age>41</Age>
<Country>USA</Country>
</Person>
<Person>
<ID>2</ID>
<Name>Regina Filange</Name>
<Age>33</Age>
<Country>Sweden</Country>
</Person>
<Person>
<ID>3</ID>
<Name>Rod Hull</Name>
<Age>67</Age>
<Country>UK</Country>
</Person>
</People>

Here, we define three data records each with an ID, name, Age, and
Country. We will use this XML file to display in the repeater. We can
do this on page load like so (we will need to Import System.Data to
use DataSet):

Protected Sub Page_Load(ByVal sender As Object, ByVal e


As System.EventArgs) Handles Me.Load
Dim xmlData As New DataSet()
xmlData.ReadXml(MapPath("data.xml"))
Repeater1.DataSource = xmlData
Repeater1.DataBind()
End Sub

Try Server Intellect for Windows Server Hosting. Quality and


Quantity!

This code simply reads the XML from the external file and then
assigns it to our Repeater to display. First though, we need to build
out our repeater template. Let's go ahead and create a HTML table
to display:

<asp:Repeater ID="Repeater1" runat="server">


<HeaderTemplate>
<table><tr><th>Name</th><th>Age</th><th>Country<
/th><th>Edit</th></tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
</td>
<td>

</td>
<td>

</td>
<td>

</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

In each of the table cells, we will place a Literal control and a


TextBox control - making the TextBox control hidden by default. We
will also assign the values of the datasource to each control:

<ItemTemplate>
<tr>
<td>
<asp:Literal ID="lit_Name" runat="server" Text='<
%# Eval("Name") %>' />
<asp:TextBox ID="fld_Name" runat="server"
Text='<%# Eval("Name") %>' Visible="false" />
</td>
<td>
<asp:Literal ID="lit_Age" runat="server" Text='<
%# Eval("Age") %>' />
<asp:TextBox ID="fld_Age" runat="server"
Text='<%# Eval("Age") %>' Columns="4"
Visible="false" />
</td>
<td>
<asp:Literal ID="lit_Country" runat="server"
Text='<%# Eval("Country") %>' />
<asp:TextBox ID="fld_Country" runat="server"
Text='<%# Eval("Country") %>' Visible="false" />
</td>
<td>
<asp:LinkButton ID="lnk_Edit" runat="server"
Text="Edit" CommandName="EditThis" />
<asp:LinkButton ID="lnk_Cancel" runat="server"
Text="Cancel" CommandName="CancelEdit"
Visible="false" />
</td>
</tr>
</ItemTemplate>
Notice we have included LinkButtons with CommandNames. We will
use these on the onItemCommand event of the Repeater. To create
a handler for this event, either select the Repeater in Design view
and double-click the onItemCommand event in the Properties
window, or add the following code (You'll also need to include the
method name in the OnItemCommand attribute on the Repeater
control):

Protected Sub Repeater1_ItemCommand(ByVal source As


Object, ByVal e As RepeaterCommandEventArgs)

End Sub

Here, we are going to check the CommandName, as we have two.


Then we will set the visibility of the Literal and TextBox controls:

Protected Sub Repeater1_ItemCommand(ByVal source As


Object, ByVal e As RepeaterCommandEventArgs)
Dim item As RepeaterItem = e.Item

Dim lit_Name As Literal =


CType(item.FindControl("lit_Name"), Literal)
Dim fld_Name As TextBox =
CType(item.FindControl("fld_Name"), TextBox)
Dim lit_Age As Literal =
CType(item.FindControl("lit_Age"), Literal)
Dim fld_Age As TextBox =
CType(item.FindControl("fld_Age"), TextBox)
Dim lit_Country As Literal =
CType(item.FindControl("lit_Country"), Literal)
Dim fld_Country As TextBox =
CType(item.FindControl("fld_Country"), TextBox)
Dim lnk_Edit As LinkButton =
CType(item.FindControl("lnk_Edit"), LinkButton)
Dim lnk_Cancel As LinkButton =
CType(item.FindControl("lnk_Cancel"), LinkButton)

If e.CommandName = "EditThis" Then


lit_Name.Visible = False
fld_Name.Visible = True
lit_Age.Visible = False
fld_Age.Visible = True
lit_Country.Visible = False
fld_Country.Visible = True
lnk_Edit.Text = "Save"
lnk_Cancel.Visible = True
ElseIf e.CommandName = "CancelEdit" Then
lit_Name.Visible = True
fld_Name.Visible = False
lit_Age.Visible = True
fld_Age.Visible = False
lit_Country.Visible = True
fld_Country.Visible = False
lnk_Edit.Text = "Edit"
lnk_Cancel.Visible = False
End If
End Sub

We used over 10 web hosting companies before we found Server


Intellect. Their dedicated servers and add-ons were setup swiftly, in
less than 24 hours. We were able to confirm our order over the
phone. They respond to our inquiries within an hour. Server
Intellect's customer support and assistance are the best we've ever
experienced.

Now if we run this web application, we will be able to click the Edit
link for each item in the XML file and we will be provided with a
textbox to edit the data. You can add a third update command to
save the data back to the XML file.
The ASPX page will look something like this:

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server" RenderMode="Inline"


UpdateMode="Conditional">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server"
OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<table><tr><th>Name</th><th>Age</th><th>Country<
/th><th>Edit</th></tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Literal ID="lit_Name" runat="server" Text='<
%# Eval("Name") %>' />
<asp:TextBox ID="fld_Name" runat="server"
Text='<%# Eval("Name") %>' Visible="false" />
</td>
<td>
<asp:Literal ID="lit_Age" runat="server" Text='<
%# Eval("Age") %>' />
<asp:TextBox ID="fld_Age" runat="server" Text='<
%# Eval("Age") %>' Columns="4" Visible="false" />
</td>
<td>
<asp:Literal ID="lit_Country" runat="server"
Text='<%# Eval("Country") %>' />
<asp:TextBox ID="fld_Country" runat="server"
Text='<%# Eval("Country") %>' Visible="false" />
</td>
<td>
<asp:LinkButton ID="lnk_Edit" runat="server"
Text="Edit" CommandName="EditThis" />
<asp:LinkButton ID="lnk_Cancel" runat="server"
Text="Cancel" CommandName="CancelEdit"
Visible="false" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</form>

And then the entire code-behind will look something like this:

Imports System.Data

Partial Class _Default


Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal


e As System.EventArgs) Handles Me.Load
Dim xmlData As New DataSet()
xmlData.ReadXml(MapPath("data.xml"))
Repeater1.DataSource = xmlData
Repeater1.DataBind()
End Sub

Protected Sub Repeater1_ItemCommand(ByVal source As


Object, ByVal e As RepeaterCommandEventArgs)
Dim item As RepeaterItem = e.Item

Dim lit_Name As Literal =


CType(item.FindControl("lit_Name"), Literal)
Dim fld_Name As TextBox =
CType(item.FindControl("fld_Name"), TextBox)
Dim lit_Age As Literal =
CType(item.FindControl("lit_Age"), Literal)
Dim fld_Age As TextBox =
CType(item.FindControl("fld_Age"), TextBox)
Dim lit_Country As Literal =
CType(item.FindControl("lit_Country"), Literal)
Dim fld_Country As TextBox =
CType(item.FindControl("fld_Country"), TextBox)
Dim lnk_Edit As LinkButton =
CType(item.FindControl("lnk_Edit"), LinkButton)
Dim lnk_Cancel As LinkButton =
CType(item.FindControl("lnk_Cancel"), LinkButton)

If e.CommandName = "EditThis" Then


lit_Name.Visible = False
fld_Name.Visible = True
lit_Age.Visible = False
fld_Age.Visible = True
lit_Country.Visible = False
fld_Country.Visible = True
lnk_Edit.Text = "Save"
lnk_Cancel.Visible = True
ElseIf e.CommandName = "CancelEdit" Then
lit_Name.Visible = True
fld_Name.Visible = False
lit_Age.Visible = True
fld_Age.Visible = False
lit_Country.Visible = True
fld_Country.Visible = False
lnk_Edit.Text = "Edit"
lnk_Cancel.Visible = False
End If
End Sub
End Class

In this tutorial, we will be looking at how we can replicate the built-in


feature of the GridView control and use a Repeater to edit data
inline and almost without delay. We will be using AJAX to call
asynchronous postbacks, and allow editing of data a row at a time.

This tutorial was written with ASP.NET 3.5 using Visual Studio 2008.
If you are using 2005 with ASP.NET 2.0, then you will need to
download the AJAX Extensions from Microsoft.

The first thing we will do is to add the ScriptManager to our ASPX


page, which will manage all of our AJAX calls:

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

Next, we can add an UpdatePanel to the page:

<asp:UpdatePanel ID="UP1" runat="server"


RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>

</HeaderTemplate>
<ItemTemplate>

</ItemTemplate>
<FooterTemplate>

</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>

We migrated our web sites to Server Intellect over one weekend and
the setup was so smooth that we were up and running right away.
They assisted us with everything we needed to do for all of our
applications. With Server Intellect's help, we were able to avoid any
headaches!

We will make use of the Header template to start a HTML table, and
the Footer template to end it. The Content template will be used for
the data we will be displaying. For this example, we will display data
from an XML file. The XML will look something like this:

<?xml version="1.0" encoding="utf-8" ?>

<People>
<Person>
<ID>1</ID>
<Name>Freddie Cosgrove</Name>
<Age>41</Age>
<Country>USA</Country>
</Person>
<Person>
<ID>2</ID>
<Name>Regina Filange</Name>
<Age>33</Age>
<Country>Sweden</Country>
</Person>
<Person>
<ID>3</ID>
<Name>Rod Hull</Name>
<Age>67</Age>
<Country>UK</Country>
</Person>
</People>

Here, we define three data records each with an ID, name, Age, and
Country. We will use this XML file to display in the repeater. We can
do this on page load like so:

protected void Page_Load(object sender, EventArgs e)


{
DataSet xmlData = new DataSet();
xmlData.ReadXml(MapPath("data.xml"));
Repeater1.DataSource = xmlData;
Repeater1.DataBind();
}
We chose Server Intellect for its dedicated servers, for our web
hosting. They have managed to handle virtually everything for us,
from start to finish. And their customer service is stellar.

This code simply reads the XML from the external file and then
assigns it to our Repeater to display. First though, we need to build
out our repeater template. Let's go ahead and create a HTML table
to display:

<asp:Repeater ID="Repeater1" runat="server">


<HeaderTemplate>
<table><tr><th>Name</th><th>Age</th><th>Country<
/th><th>Edit</th></tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>

</td>
<td>

</td>
<td>

</td>
<td>

</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

In each of the table cells, we will place a Literal control and a


TextBox control - making the TextBox control hidden by default. We
will also assign the values of the datasource to each control:

<ItemTemplate>
<tr>
<td>
<asp:Literal ID="lit_Name" runat="server" Text='<
%# Eval("Name") %>' />
<asp:TextBox ID="fld_Name" runat="server"
Text='<%# Eval("Name") %>' Visible="false" />
</td>
<td>
<asp:Literal ID="lit_Age" runat="server" Text='<
%# Eval("Age") %>' />
<asp:TextBox ID="fld_Age" runat="server"
Text='<%# Eval("Age") %>' Columns="4"
Visible="false" />
</td>
<td>
<asp:Literal ID="lit_Country" runat="server"
Text='<%# Eval("Country") %>' />
<asp:TextBox ID="fld_Country" runat="server"
Text='<%# Eval("Country") %>' Visible="false" />
</td>
<td>
<asp:LinkButton ID="lnk_Edit" runat="server"
Text="Edit" CommandName="EditThis" />
<asp:LinkButton ID="lnk_Cancel" runat="server"
Text="Cancel" CommandName="CancelEdit"
Visible="false" />
</td>
</tr>
</ItemTemplate>

Notice we have included LinkButtons with CommandNames. We will


use these on the onItemCommand event of the Repeater. To create
a handler for this event, either select the Repeater in Design view
and double-click the onItemCommand event in the Properties
window, or add the following code (You'll also need to include the
method name in the OnItemCommand attribute on the Repeater
control):

protected void Repeater1_ItemCommand(object source,


RepeaterCommandEventArgs e)
{

Here, we are going to check the CommandName, as we have two.


Then we will set the visibility of the Literal and TextBox controls:

protected void Repeater1_ItemCommand(object source,


RepeaterCommandEventArgs e)
{
RepeaterItem item = e.Item;

Literal lit_Name = (Literal)item.FindControl("lit_Name");


TextBox fld_Name =
(TextBox)item.FindControl("fld_Name");
Literal lit_Age = (Literal)item.FindControl("lit_Age");
TextBox fld_Age = (TextBox)item.FindControl("fld_Age");
Literal lit_Country =
(Literal)item.FindControl("lit_Country");
TextBox fld_Country =
(TextBox)item.FindControl("fld_Country");
LinkButton lnk_Edit =
(LinkButton)item.FindControl("lnk_Edit");
LinkButton lnk_Cancel =
(LinkButton)item.FindControl("lnk_Cancel");

if (e.CommandName == "EditThis")
{
lit_Name.Visible = false;
fld_Name.Visible = true;
lit_Age.Visible = false;
fld_Age.Visible = true;
lit_Country.Visible = false;
fld_Country.Visible = true;
lnk_Edit.Text = "Save";
lnk_Cancel.Visible = true;
}
else if (e.CommandName == "CancelEdit")
{
lit_Name.Visible = true;
fld_Name.Visible = false;
lit_Age.Visible = true;
fld_Age.Visible = false;
lit_Country.Visible = true;
fld_Country.Visible = false;
lnk_Edit.Text = "Edit";
lnk_Cancel.Visible = false;
}
}

We moved our web sites to Server Intellect and have found them to
be incredibly professional. Their setup is very easy and we were up
and running in no time.

Now if we run this web application, we will be able to click the Edit
link for each item in the XML file and we will be provided with a
textbox to edit the data. You can add a third update command to
save the data back to the XML file.
The ASPX page will look something like this:

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server" RenderMode="Inline"


UpdateMode="Conditional">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server"
OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<table><tr><th>Name</th><th>Age</th><th>Country<
/th><th>Edit</th></tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Literal ID="lit_Name" runat="server" Text='<
%# Eval("Name") %>' />
<asp:TextBox ID="fld_Name" runat="server"
Text='<%# Eval("Name") %>' Visible="false" />
</td>
<td>
<asp:Literal ID="lit_Age" runat="server" Text='<
%# Eval("Age") %>' />
<asp:TextBox ID="fld_Age" runat="server" Text='<
%# Eval("Age") %>' Columns="4" Visible="false" />
</td>
<td>
<asp:Literal ID="lit_Country" runat="server"
Text='<%# Eval("Country") %>' />
<asp:TextBox ID="fld_Country" runat="server"
Text='<%# Eval("Country") %>' Visible="false" />
</td>
<td>
<asp:LinkButton ID="lnk_Edit" runat="server"
Text="Edit" CommandName="EditThis" />
<asp:LinkButton ID="lnk_Cancel" runat="server"
Text="Cancel" CommandName="CancelEdit"
Visible="false" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</form>

And then the entire code-behind will look something like this:

using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

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


{
protected void Page_Load(object sender, EventArgs e)
{
DataSet xmlData = new DataSet();
xmlData.ReadXml(MapPath("data.xml"));
Repeater1.DataSource = xmlData;
Repeater1.DataBind();
}

protected void Repeater1_ItemCommand(object source,


RepeaterCommandEventArgs e)
{
RepeaterItem item = e.Item;

Literal lit_Name =
(Literal)item.FindControl("lit_Name");
TextBox fld_Name =
(TextBox)item.FindControl("fld_Name");
Literal lit_Age = (Literal)item.FindControl("lit_Age");
TextBox fld_Age =
(TextBox)item.FindControl("fld_Age");
Literal lit_Country =
(Literal)item.FindControl("lit_Country");
TextBox fld_Country =
(TextBox)item.FindControl("fld_Country");
LinkButton lnk_Edit =
(LinkButton)item.FindControl("lnk_Edit");
LinkButton lnk_Cancel =
(LinkButton)item.FindControl("lnk_Cancel");

if (e.CommandName == "EditThis")
{
lit_Name.Visible = false;
fld_Name.Visible = true;
lit_Age.Visible = false;
fld_Age.Visible = true;
lit_Country.Visible = false;
fld_Country.Visible = true;
lnk_Edit.Text = "Save";
lnk_Cancel.Visible = true;
}
else if (e.CommandName == "CancelEdit")
{
lit_Name.Visible = true;
fld_Name.Visible = false;
lit_Age.Visible = true;
fld_Age.Visible = false;
lit_Country.Visible = true;
fld_Country.Visible = false;
lnk_Edit.Text = "Edit";
lnk_Cancel.Visible = false;
}
}
}

In this tutorial, we will be looking at how to use AJAX to dynamically


display the time spent on a web page.

This tutorial was written with ASP.NET 3.5 using Visual Studio 2008.
If you are using 2005 with ASP.NET 2.0, then you will need to
download the AJAX Extensions from Microsoft.
In order to display the time spent on the page, we will have to
create an UpdatePanel that updates every second. In order for this
to not affect the rest of the page, we will put other functionality in
another Update Panel. To programmatically update the time, we will
use an AJAX Timer control. But first, let us begin by adding a
ScriptManager control to our ASPX page:

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

The next thing to do is add our UpdatePanel that will display the
time spent on the page:

<asp:UpdatePanel ID="UP_Timer" runat="server"


RenderMode="Inline" UpdateMode="Always">
<Triggers>

</Triggers>
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>

We are using Server Intellect and have found that by far, they are
the most friendly, responsive, and knowledgeable support team
we've ever dealt with!

Notice that we have included the triggers tag, as well as the content
template. The trigger we are going to use will be an AJAX Timer
control. Let's add that in now, as well as set the Trigger attributes:

<asp:UpdatePanel ID="UP_Timer" runat="server"


RenderMode="Inline" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1"
EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server"
Interval="1000" />
<asp:Literal ID="lit_Timer" runat="server" /><br />
<asp:HiddenField ID="hid_Ticker" runat="server"
Value="0" />
</ContentTemplate>
</asp:UpdatePanel>

We add an AsyncPostBackTrigger and set the control ID and Event


Name to match our Timer control. We also set the Interval of the
Timer's tick event to 1000 milliseconds. We have added a Literal
control to display the time spent on the page, and then a
HiddenField to store that value. We add code to the code-behind
that will run every second, on the Tick event of the Timer control
(we can do this by simply adding the code manually, or double-
clicking the timer control in Design view):

Protected Sub Page_Load(ByVal sender As Object, ByVal e


As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
hid_Ticker.Value = New TimeSpan(0, 0, 0).ToString()
End If
End Sub

Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e


As System.EventArgs) Handles Timer1.Tick
hid_Ticker.Value =
TimeSpan.Parse(hid_Ticker.Value).Add(New TimeSpan(0,
0, 1)).ToString()
lit_Timer.Text = "Time spent on this page: " +
hid_Ticker.Value.ToString()
End Sub

We used over 10 web hosting companies before we found Server


Intellect. Their dedicated servers and add-ons were setup swiftly, in
less than 24 hours. We were able to confirm our order over the
phone. They respond to our inquiries within an hour. Server
Intellect's customer support and assistance are the best we've ever
experienced.

First, on page load we are assigning a new value to the hidden field,
of type TimeSpan. This TimeSpan is 0 hours, 0 minutes, and 0
seconds. Then on each Tick event, we add one second to that value,
then display it in the Literal control. If we now run this page, we will
see the page programmatically and seamlessly count up the time
spent on the page.
To demonstrate that this will not interfere with other functions on
the page, let's go ahead and add another Update Panel:

<asp:UpdatePanel ID="UP_Name" runat="server"


RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
Add your name: <asp:TextBox ID="fld_Name"
runat="server" /><br />
<br />
<asp:Button ID="btn_Submit" runat="server"
Text="Submit" /><br />
<asp:Literal ID="lit_Name" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>

Here, we will ask for the name of the visitor and then display it back
to them without posting back. We do this with the following code:

Protected Sub btn_Submit_Click(ByVal sender As Object,


ByVal e As System.EventArgs) Handles btn_Submit.Click
lit_Name.Text = "Thanks. Your name is: " &
fld_Name.Text
End Sub

Our ASPX page and code-behind will look something like this:

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP_Timer" runat="server"


RenderMode="Inline" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1"
EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server"
Interval="1000" />
<asp:Literal ID="lit_Timer" runat="server"
/><br />
<asp:HiddenField ID="hid_Ticker" runat="server"
Value="0" />
</ContentTemplate>
</asp:UpdatePanel>

<br />

<asp:UpdatePanel ID="UP_Name" runat="server"


RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
Add your name: <asp:TextBox ID="fld_Name"
runat="server" /><br />
<br />
<asp:Button ID="btn_Submit" runat="server"
Text="Submit" /><br />
<asp:Literal ID="lit_Name" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

Try Server Intellect for Windows Server Hosting. Quality and


Quantity!

Partial Class _Default


Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal


e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
hid_Ticker.Value = New TimeSpan(0, 0,
0).ToString()
End If
End Sub

Protected Sub Timer1_Tick(ByVal sender As Object, ByVal


e As System.EventArgs) Handles Timer1.Tick
hid_Ticker.Value =
TimeSpan.Parse(hid_Ticker.Value).Add(New
TimeSpan(0, 0, 1)).ToString()
lit_Timer.Text = "Time spent on this page: " +
hid_Ticker.Value.ToString()
End Sub

Protected Sub btn_Submit_Click(ByVal sender As Object,


ByVal e As System.EventArgs) Handles btn_Submit.Click
lit_Name.Text = "Thanks. Your name is: " &
fld_Name.Text
End Sub
End Class

In this tutorial, you will learn how to use Client-Side AJAX. We will be
using JavaScript to create a AJAX Client Library, and then reference
the JavaScript function from our ASPX page.
This tutorial was written with and intended for users of Microsoft
Visual Studio.NET 2008, but can be recreated with version 2005,
providing the AJAX Extension is installed, which is available for free
download from Microsoft at this link.

The first thing we can do, once we have our project and ASPX page
open in Visual Studio.NET, is to right-click the project in Solution
Explorer, and then choose Add New Item.. AJAX Client Library. This
will be our JavaScript Client Library, were we can place all of our
functions to use on the page. For this example, though, we shall
create just one.
Let's go ahead and add a simple function:

/// <reference name="MicrosoftAjax.js"/>

function getMessage() {
alert("Thanks for clicking the message button.");
}

if (typeof (Sys) !== "undefined")


Sys.Application.notifyScriptLoaded();

We used over 10 web hosting companies before we found Server


Intellect. Their dedicated servers and add-ons were setup swiftly, in
less than 24 hours. We were able to confirm our order over the
phone. They respond to our inquiries within an hour. Server
Intellect's customer support and assistance are the best we've ever
experienced.
The comment on this first line is inserted automatically by VS. It
allows IntelliSense to be shown for the Microsoft AJAX Library.

In this function, we are simply displaying an alert to the user that


they clicked the button.
Next, we need to add a ScriptManager to the page to manage our
AJAX calls, and also reference our Client Library. We do this by
adding it between the Script tags like so:

<form id="form1" runat="server">


<asp:ScriptManager ID="SM1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/ClientLibrary.js" />
</Scripts>
</asp:ScriptManager>
</form>

We chose Server Intellect for its dedicated servers, for our web
hosting. They have managed to handle virtually everything for us,
from start to finish. And their customer service is stellar.

To implement this button click, we insert script tags in the HEAD


section of the HTML on our ASPX page:

<script type="text/javascript">

</script>

Here we will place the function that will be assigned to our button
click, and will reference the function we created in our Library. It
should look something like this:

<script type="text/javascript">
function clickButton1() {
getMessage();
}
</script>

Server Intellect offers Windows Hosting Dedicated Servers at


affordable prices. I'm very pleased!

This very simple function is calling the function in our Client Library,
and will display the alert box when executed. Now we need to
create a button to execute this. Go back to below our
ScriptManager, and add a button:

<form id="form1" runat="server">


<asp:ScriptManager ID="SM1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/ClientLibrary.js" />
</Scripts>
</asp:ScriptManager>

<asp:Button ID="btn_JSClick1" runat="server"


Text="Click Me" OnClientClick="clickButton1()" />
</form>

We use the OnClientClick attribute to call the function in the HEAD


of our ASPX document, which in turn calls the function in our
Library, thus displaying an alert.

In this tutorial, we will be looking at how to use the


AnimationExtender in the AJAX Control Toolkit from Microsoft. This
tutorial is aimed toward users of Visual Studio.NET 2008, but should
work with 2005 providing the AJAX Extensions are installed.

This tutorial uses the Microsoft AJAX.NET Toolkit, which can be


downloaded from the following link:
www.asp.net/Ajax/ajaxcontroltoolkit/

If you need help installing the Toolkit, please see this article.

In this tutorial, we will be explore using the AnimationExtender to


utilize JavaScript to animate controls in our web application. The
first thing we will need to do is to add a ScriptManager to our ASPX
page, which will allow us to implement AJAX:

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

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

The next thing we will do is add an ASP.NET Panel control onto our
page and drag an AnimationExtender from the Toolkit toolbox to our
ASPX page:

.Animation1
{
position: absolute;
padding:3px;
border: solid 1px #000;
}

..

<form id="form1" runat="server">


<asp:ScriptManager ID="SM1" runat="server" />
<br />
<asp:Panel ID="panel_Animated" runat="server"
CssClass="Animation1">
Animation imminent.
</asp:Panel>
<br />
<cc1:AnimationExtender ID="AnimationExtender1"
runat="server" TargetControlID="panel_Animated">
</cc1:AnimationExtender>
</form>

Notice that we have declared a CSS class for our Panel to use. If we
do not make the Panel's position absolute, then we will not be able
to manipulate its position on the page.
Now in order to actually animate the Panel, we are required to insert
further parameters into the Extender, for example:

<cc1:AnimationExtender ID="AnimationExtender1"
runat="server" TargetControlID="panel_Animated">
<Animations>
<OnLoad>
<Sequence>
<Move Horizontal="300" Duration="1"
Fps="20" />
<FadeOut Duration="1" Fps="20" />
</Sequence>
</OnLoad>
</Animations>
</cc1:AnimationExtender>

If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

We keep everything within the Extender tags, and notice that they
are not all specified as attributes. There are a number of triggers we
can use for animations, which include OnLoad, OnClick,
OnMouseOver, OnMouseOut, OnHoverOver, and OnHoverOut. In this
example we are using the OnLoad trigger so that when the page
loads, the Panel will be animated 300 pixels horizontally over a
period of 1 second. We are also able to set the number of frames
per second with the Fps attribute.

Now when this page is run, the Panel will be animated as soon as
the page is done loading. Now, if we wanted to animate on a button
click, then we would use the OnClick trigger.
To do this, let's add a button and another panel to our ASPX page:

.Animation2
{
display:none;
position:absolute;
width:1px;
height:1px;
left:400px;
top:600px;
padding:3px;
border:solid 1px #000;
}

..

<asp:Button ID="btn_Animate" runat="server"


Text="Animate" OnClientClick="return false;" />
<br />
<asp:Panel ID="panel_Animated2" runat="server"
CssClass="Animation2">
Animation2 imminent.
</asp:Panel>
<br />
<cc1:AnimationExtender ID="AnimationExtender2"
runat="server" TargetControlID="btn_Animate">
<Animations>
<OnClick>
<Sequence AnimationTarget="panel_Animated2">
<EnableAction AnimationTarget="btn_Animate"
Enabled="false" />
<StyleAction Attribute="display" Value="Block"
/>
<Parallel>
<FadeIn Duration="1" Fps="20" />
<Scale Duration="1" Fps="20"
ScaleFactor="30.0" Center="true" />
</Parallel>
</Sequence>
</OnClick>
</Animations>
</cc1:AnimationExtender>

We are using Server Intellect and have found that by far, they are
the most friendly, responsive, and knowledgeable support team
we've ever dealt with!

We create another CSS class for the new panel and notice we also
change the OnLoad trigger as in the last example to OnClick. We are
also required to set an AnimationTarget as our TargetControl is now
the button, not the panel. The animation sequence is similar to the
last, except we use Scale to increase the size of the Panel as well.

Our ASPX page looks something like this:

<style>
.Animation1
{
position: absolute;
padding:3px;
border: solid 1px #000;
}
.Animation2
{
display:none;
position:absolute;
width:1px;
height:1px;
left:400px;
top:600px;
padding:3px;
border:solid 1px #000;
}
</style>

..

<form id="form1" runat="server">


<asp:ScriptManager ID="SM1" runat="server" />
<br />
<asp:Panel ID="panel_Animated" runat="server"
CssClass="Animation1">
Animation imminent.
</asp:Panel>
<br />
<cc1:AnimationExtender ID="AnimationExtender1"
runat="server" TargetControlID="panel_Animated">
<Animations>
<OnLoad>
<Sequence>
<Move Horizontal="300" Duration="1"
Fps="20" />
<FadeOut Duration="1" Fps="20" />
</Sequence>
</OnLoad>
</Animations>
</cc1:AnimationExtender>
<br />
<br />
<asp:Button ID="btn_Animate" runat="server"
Text="Animate" OnClientClick="return false;" />
<br />
<asp:Panel ID="panel_Animated2" runat="server"
CssClass="Animation2">
Animation2 imminent.
</asp:Panel>
<br />
<cc1:AnimationExtender ID="AnimationExtender2"
runat="server" TargetControlID="btn_Animate">
<Animations>
<OnClick>
<Sequence
AnimationTarget="panel_Animated2">
<EnableAction
AnimationTarget="btn_Animate"
Enabled="false" />
<StyleAction Attribute="display"
Value="Block" />
<Parallel>
<FadeIn Duration="1" Fps="20" />
<Scale Duration="1" Fps="20"
ScaleFactor="30.0" Center="true" />
</Parallel>
</Sequence>
</OnClick>
</Animations>
</cc1:AnimationExtender>
</form>

In this tutorial, we will be looking at just a few of the controls in the


AJAX Control Toolkit from Microsoft. This tutorial is aimed toward
users of Visual Studio.NET 2008.
We will be looking at the following controls:
TextBoxWatermarkExtender, ConfirmButtonExtender,
DragPanelExtender, and the ModalPopupExtender.

This tutorial uses the Microsoft AJAX.NET Toolkit, which can be


downloaded from the following link:
www.asp.net/Ajax/ajaxcontroltoolkit/

If you need help installing the Toolkit, please see this article.

To get started, we will begin a C# project (although it doesn't really


matter which language we choose, as we will just be covering the
ASPX implementation of the controls).
Once we have our project open in VS, we should see the AJAX
Control Toolkit in our toolbox. Let's start off by making sure we have
the ScriptManager on our page:

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

Now we can add the AJAX Controls to our page. Let's start with the
TextBoxWatermarkExtender. This AJAX Control extends the ASP.NET
TextBox Control to allow you to set a 'Watermark' to the textbox.
When the user clicks on the textbox, the 'Watermark' disappears,
and they can input their own text. This is useful for providing more
information to users about what is required in the textbox.
So let's start by adding a regular textbox to the page:

<asp:TextBox ID="fld_Watermark" runat="server" />

We used over 10 web hosting companies before we found Server


Intellect. Their dedicated servers and add-ons were setup swiftly, in
less than 24 hours. We were able to confirm our order over the
phone. They respond to our inquiries within an hour. Server
Intellect's customer support and assistance are the best we've ever
experienced.

Now if we drag onto the page the WatermarkExtender from the


Toolkit, we should see two things: one, the
TextBoxWatermarkExtender custom control tag; and two, the
Register directive at the top of the page, which allows us to use the
AJAX Controls:

<%@ Register Assembly="AjaxControlToolkit"


Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

..

<cc1:TextBoxWatermarkExtender
ID="fld_Watermark_Extender" runat="server"
TargetControlID="fld_Watermark"
WatermarkText="Input text"
WatermarkCssClass="WaterMarkClass" />

Notice that we set further properties of the Extender than was given
to us by default. We set the TargetControl to that of the textbox, the
WatermarkText to the text we want to be specified in the textbox,
and then a CSS class to make the text gray:

.WaterMarkClass
{
color:Gray;
}

If you're ever in the market for some great Windows web hosting,
try Server Intellect. We have been very pleased with their services
and most importantly, technical support.

Now if you run this application, you will see that there is gray text in
the textbox by default, but as soon as you click in it, it disappears.
Similarly, if the textbox is empty when it loses focus, then the
Watermark re-appears.

The next Extender we will look at is the ConfirmButtonExtender.


Let's go ahead and add a button to our existing form, and then drag
a ConfirmButtonExtender from the toolkit:

Input text:
<asp:TextBox ID="fld_Watermark" runat="server" />
<cc1:TextBoxWatermarkExtender
ID="fld_Watermark_Extender" runat="server"
TargetControlID="fld_Watermark"
WatermarkText="Input text"
WatermarkCssClass="WaterMarkClass" />

<cc1:ConfirmButtonExtender ID="ConfirmButtonExtender1"
runat="server" ConfirmOnFormSubmit="true"
ConfirmText="Are you sure you want to Submit this
form?" TargetControlID="button_Submit" />
<asp:Button ID="button_Submit" runat="server"
Text="Submit" />

Notice that the Extender uses the same tag prefix as the
Watermark, because they are both from the Toolkit.
Again, we add a couple of extra attributes to the Extender than is
given to us by default: ConfirmText will be displayed to the user in a
JavaScript popup box when the button is clicked; and we also
declare which control to use the Extender with (button_Submit).

If the web application is run at this point, you will see that a
standard JavaScript popup box appears when you click on the
button. The popup will give you Ok and Cancel buttons.

Next, we will take a look at the DragPanelExtender. For this one, we


need to encapsulate our existing controls in an ASP.NET Panel. We
will also place the extender on our page from the Toolkit. Let's do
this now:

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


[DRAG ME]<br />
Input text:
<asp:TextBox ID="fld_Watermark" runat="server" />
<cc1:TextBoxWatermarkExtender
ID="fld_Watermark_Extender" runat="server"
TargetControlID="fld_Watermark"
WatermarkText="Input text"
WatermarkCssClass="WaterMarkClass" />

<cc1:ConfirmButtonExtender
ID="ConfirmButtonExtender1" runat="server"
ConfirmOnFormSubmit="true"
ConfirmText="Are you sure you want to Submit this
form?" TargetControlID="button_Submit" />
<asp:Button ID="button_Submit" runat="server"
Text="Submit" />
</asp:Panel>
<br />
<cc1:DragPanelExtender ID="DragPanelExtender1"
runat="server" TargetControlID="panel_Drag" />

If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!
We surround our existing controls with a Panel and name it, then we
add the Extender outside of the panel and reference the panel name
in the TargetControlID of the Extender. Once we have done this,
ASP.NET will do the rest. Run the web application and try to drag the
panel around the page to place it where you want.
NOTE: You will only be able to place it where HTML has been
rendered.

Finally, we will take a look at the ModalPopupExtender, which is


probably the most exciting. Instead of using a regular JavaScript
popup window, we can use a panel to appear in the middle of the
screen, and gray-out the rest of the form. To do this, we need to
implement a little CSS also.
The first thing to do is to add a button to initiate the popup, and
then create another Panel which will act as the popup. We will also
need to drag the Extender from the Toolkit:

.GrayedOut
{
background-color:Gray;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
.ModalPopup
{
background-color:#FFF;
padding:15px;
border: solid 1px #000;
}

..

<asp:Button ID="btn_Popup" runat="server" Text="Click to


Pop" />
<cc1:ModalPopupExtender ID="ModalPopupExtender1"
runat="server" CancelControlID="btn_Cancel"
BackgroundCssClass="GrayedOut"
OkControlID="btn_Ok" TargetControlID="btn_Popup"
PopupControlID="panel_ModalPopup" />
<asp:Panel ID="panel_ModalPopup" runat="server"
CssClass="ModalPopup">
This is a Modal Popup Window.<br />
<br />
<asp:Button ID="btn_Ok" runat="server" Text="OK" />
<asp:Button ID="btn_Cancel" runat="server"
Text="Cancel" />
</asp:Panel>

Notice we have set the TargetControl and PopupControl attributes of


the Extender, which identifies both the control to initiate the popup
(the button), and also the control which will be the popup (the
panel). We also set the CssClass attribute so that we can alter the
look - fading out the background whilst it is inaccessible. We use the
opacity CSS property, but also include variations to cover different
browsers.

Now if we run this web application, we will see that we get a very
nice popup window when we click the button, and the rest of the
page is grayed out, and disabled, until we click a button in the
popup to close it.

This tutorial was created with and aimed toward users of Visual
Studio.NET 2008. However, 2005 can be used if Microsoft's ASP.NET
AJAX Extensions, which can be downloaded here, is installed.
Also, if using 2005, some additional steps may be required that are
not listed in this article.

As with the Server-Side ASP.NET Life Cycle, the Client-Side also


raises events on PostBack. In this example, we will be looking at the
events raised on the Client-Side, and will also output the trace
messages to a text box.

Server Intellect assists companies of all sizes with their hosting


needs by offering fully configured server solutions coupled with
proactive server management services. Server Intellect specializes
in providing complete internet-ready server solutions backed by
their expert 24/365 proactive support team.

Because we will be working with the Client-Side, we have to use


JavaScript as the code will be run in the browser, as opposed to on
the server. To start, we will create our ASPX page. Go ahead and
add two buttons and also a HTML TextArea:

<form id="form1" runat="server">


<asp:Button ID="Button1" runat="server"
Text="Asynchronous PostBack" />
<asp:Button ID="Button2" runat="server" Text="Normal
PostBack" />
<br /><br />
<TextArea ID="TraceConsole" cols="55"
rows="10"></TextArea>
</form>

Try Server Intellect for Windows Server Hosting. Quality and


Quantity!

If using Microsoft Internet Explorer, we are required to add the


TextArea and give it an ID of TraceConsole in order to view the trace
messages. In FireFox however, we can use the console within the
FireBug plugin.
We will be using two buttons - one inside the UpdatePanel, and one
out - so that we can call both an Asynchronous PostBack and a
Normal PostBack. This way we can compare the differences
between the trace messages.
Let's go ahead and add the ScriptManager and UpdatePanel. In
Visual Studio.NET 2008, this is simply a matter of adding the tags:

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server">


<ContentTemplate>
<asp:Button ID="Button1" runat="server"
Text="Asynchronous PostBack" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="Normal
PostBack" />
<br /><br />
<TextArea ID="TraceConsole" cols="55"
rows="10"></TextArea>
</form>

Server Intellect offers Windows Hosting Dedicated Servers at


affordable prices. I'm very pleased!

Once again, because we're working with the Client Side, we will not
be adding code-behind logic. Instead, we use JavaScript to run in the
browser on the client side.
The events that we'll be using that happen on the client-side are as
follows:
Application.init - occurs when a page is first requested from the
server;
PageRequestManager.initializeRequest - occurs before an
Asynchronous request initiates;
PageRequestManager.beginRequest - occurs before an
Asynchronous request initiates;
PageRequestManager.pageLoading - occurs before an UpdatePanel
is updated, but after an Asynchronous response from the server is
received;
PageRequestManager.pageLoaded - occurs after an UpdatePanel is
updated, and after an Asynchronous response from the server is
received;
Application.load - occurs during PostBacks;
PageRequestManager.endRequest - occurs after an Asyncronous
response;
Application.unload - occurs before the application unloads (user
leaves or refreshes), as indicated by the JavaScript alert we used in
the code below.
<script type="text/javascript">
Sys.Application.add_init(application_init);

function application_init()
{
Sys.Debug.trace("Application.Init");

var prm =
Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(prm_initializeRequest);
prm.add_beginRequest(prm_beginRequest);
prm.add_pageLoading(prm_pageLoading);
prm.add_pageLoaded(prm_pageLoaded);
prm.add_endRequest(prm_endRequest);
}

function pageLoad()
{
Sys.Debug.trace("Application.Load");
}

function prm_initializeRequest()
{
Sys.Debug.trace("PageRequestManager.initializeRequ
est");
}

function prm_beginRequest()
{
Sys.Debug.trace("PageRequestManager.beginRequest
");
}

function prm_pageLoading()
{
Sys.Debug.trace("PageRequestManager.pageLoading"
);
}

function prm_pageLoaded()
{
Sys.Debug.trace("PageRequestManager.pageLoaded"
);
}

function prm_endRequest()
{
Sys.Debug.trace("PageRequestManager.endRequest")
;
}

function pageUnload()
{
alert("Application.Unload");
}
</script>

Now when we run our Web Application, you will notice that the
Async button will set all the values to True except PreInit. This is
because the IsAsyncPostBack Property gets updated after this event
is called.

This tutorial was created with and aimed toward users of Visual
Studio.NET 2008. However, 2005 can be used if Microsoft's ASP.NET
AJAX Extensions, which can be downloaded here, is installed.
Also, if using 2005, some additional steps may be required that are
not listed in this article.

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

In this example, we will be looking briefly at the Life Cycle of an


ASPX page, and how an Asynchronous PostBack still follows the
same events as a normal PostBack. We will be adding two buttons
and a BulletedList to our ASPX page:

<form id="form1" runat="server">


<asp:Button ID="Button1" runat="server" Text="Async
PostBack" />
<br />
<asp:BulletedList ID="BulletedList1" runat="server" />
<br />
<asp:Button ID="Button2" runat="server" Text="Normal
PostBack" />
</form>

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

We will use the Buttons to post back the page and then we will
assign the datasource of the BulletedList in the code-behind. We will
be outputting the results of the following four events:
Page_PreInit, Page_Init, Page_Load, and Page_PreRender.

We will set a Frue or False on each of these events if it's current


state is in AsyncPostBack. This means that we will be able to tell
which events are fired, if we put one button inside the UpdatePanel,
and one outside of it. This way, way can call both an Async PostBack
and a full PostBack and compare the True/False responses.
Let's go ahead and add the ScriptManager and the UpdatePanel:

<form id="form1" runat="server">


<asp:ScriptManager ID="SM1" runat="server" />
<asp:UpdatePanel ID="UP1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server"
Text="Async PostBack" />
<br />
<asp:BulletedList ID="BulletedList1"
runat="server" />
<br />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="Normal
PostBack" />
</form>

Need help with Windows Dedicated Hosting? Try Server Intellect. I'm
a happy customer!

Now we have our form set-up as we want it, we can turn our
attention to the code-behind. Here, we will add to an ArrayList on
each of our events.
By doing this, we will be able to see which events are called when
we alternate between Async and Normal PostBacks. Here is what
our code will look like:

using System.Collections;

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


{
public ArrayList _log = new ArrayList();

void Page_PreInit()
{
_log.Add("Page_PreInit " + SM1.IsInAsyncPostBack);
}

void Page_Init()
{
_log.Add("Page_Init " + SM1.IsInAsyncPostBack);
}

void Page_Load()
{
_log.Add("Page_Load " + SM1.IsInAsyncPostBack);
}

void Page_PreRender()
{
_log.Add("Page_PreRender " +
SM1.IsInAsyncPostBack);

BulletedList1.DataSource = _log;
BulletedList1.DataBind();
}
}

Now when we run our Web Application, you will notice that the
Async button will set all the values to True except PreInit. This is
because the IsAsyncPostBack Property gets updated after this event
is called.

This tutorial was created with and aimed toward users of Visual
Studio.NET 2008. 2005 can be used, but Microsoft's ASP.NET AJAX
Extensions, which can be downloaded here, must be installed.
Also, if using 2005, some additional steps may be required that are
not listed in this article.

Microsoft have a Control Toolkit that is optional and not included


with the .NET Framework, which can be downloaded from
www.codeplex.com/AjaxControlToolkit. This Toolkit is constantly
being updated and consists mainly of AJAX Extenders for existing
ASP.NET Controls.
In this tutorial, we will be looking at the HoverMenu extender to add
a hoever menu (or description) to a Repeater Control, which extends
an ASP.NET Repeater.

We moved our web sites to Server Intellect and have found them to
be incredibly professional. Their setup is very easy and we were up
and running in no time.

To get started, we need to first download the AJAX Control Toolkit


from Microsoft, using the link above. If you do not already have the
Toolkit installed on your machine, get the ZIP file with the source
code.
Once downloaded, extract to a folder on your computer and start
Visual Studio. We will add the toolkit to the toolbox within VS. Open
up the toolbox and right-click in an empty space, then choose Add
Tab. Give it a name like AJAX Toolkit, or AJAX Extenders. Then when
it is added, right-click under the tab and select Choose Items. Wait
for the Window to appear, and then click the Browse button
under .NET Framework Components. Navigate to the folder you
extracted to and select the AjaxControlToolkit.dll in the
SampleWebSite/Bin/ directory. VS will then add all the AJAX Toolkit
controls to the toolbox.

Now we are able to add any of these controls to our web


applications. We must still remember the ScriptManager, as all of
these controls are AJAX-enabled. So to start, let's add the
ScriptManager control:

<form id="form1" runat="server">


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

We used over 10 web hosting companies before we found Server


Intellect. Their dedicated servers and add-ons were setup swiftly, in
less than 24 hours. We were able to confirm our order over the
phone. They respond to our inquiries within an hour. Server
Intellect's customer support and assistance are the best we've ever
experienced.

In this example, we will be using a Repeater control to display menu


items from a SQL Database. Let's go ahead and add the Repeater,
then we will go about creating the table and data access class.

<form id="form1" runat="server">


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

<asp:Repeater ID="Repeater1" runat="server">


<ItemTemplate>

</ItemTemplate>
</asp:Repeater>
</form>

Try Server Intellect for Windows Server Hosting. Quality and


Quantity!

Now we have our Repeater control, let's add our database. Right-
click the App_Data folder in Solution Explorer and choose Add New
Item.. SQL Server Database. When it appears in Server Explorer,
right-click the Tables folder and choose Add New Table. In table
designer, let's create three columns - ID, MenuText and MenuInfo,
with data types of bigint, varchar(25) and varchar(50) respectively.
Once our columns are created, we can save the table and give it a
name. Then, right-click the table name in Server Explorer and
choose Show Table Data. Let's add some data to the table to pull
from, which we'll use to build our menu. The MenuText will be used
for the link, and the MenuInfo will be used for the pop-up description
of the link.

Now that we have some data, all we need is to retrieve and display
it. Right-click the Stored Procedures folder in Server Explorer and
choose to add a new one. Let's create a Stored Procedure to get the
data from our table:

CREATE PROCEDURE dbo.GetMenuInfo

AS
SELECT * FROM tblMenu
Once we save this Stored Procedure, the CREATE keyword will
change to ALTER and this will allow us to edit it if need be.

Let's go ahead and drag a SqlDataSource control onto our ASPX


page, then click into design view and click the Smart Tag of the
SqlDataSource, then Configure Data Source. Choose the database
name from the drop-down and follow the instructions to select all
data from the table we created. Finally, click finish and then delete
the SqlDataSource control. This was a quick way to build our
Connection String in the Web.config file:

<connectionStrings>
<add name="ConnectionString" connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|
DataDirectory|\Database.mdf;Integrated
Security=True;User Instance=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>

Server Intellect offers Windows Hosting Dedicated Servers at


affordable prices. I'm very pleased!

We will be using this connection string to connect to and retrieve


data from our database.
Next up, right-click your project folder in Solution Explorer, and if
you don't already have an App_Code folder, choose Add ASP.NET
Folder > App_Code. Now right-click the App_Code folder and choose
to Add New Item.. Class. Give it a descriptive name, I chose
Methods, then add the following using statements:

using System.Web.Configuration;
using System.Data.SqlClient;

We have added these references because we will be using them to


get our Connection String from the Web.config and also to connect
to our database.
We will be creating a method to use the Stored Procedure we
created earlier, that will retrieve the data from the database. This is
how we do it:

/// <summary>
/// Gets MenuInfo from tblMenu
/// </summary>
/// <returns>DataTable of MenuInfo in tblMenu</returns>
public static DataTable GetMenuInfo()
{
DataTable MenuInfo = new DataTable();
SqlConnection connection = new
SqlConnection(WebConfigurationManager.ConnectionStrings["Con
nectionString"].ToString());
try
{
SqlCommand cmd = new SqlCommand("GetMenuInfo",
connection);
cmd.CommandType = CommandType.StoredProcedure;

connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(MenuInfo);
connection.Close();
}
catch
{
connection.Close();
}
return MenuInfo;
}

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

Notice that when using Stored Procedures, we reference the Stored


Procedure name, and then set the CommandType.
This method will return a DataTable of all the Menu Items in the
database. Now we can call this in the back-end and set to the
Repeater's DataSource:

protected void Page_Load(object sender, EventArgs e)


{
Repeater1.DataSource = Methods.GetMenuInfo();
Repeater1.DataBind();
}

Next up, to make use of this data and add the HoverMenu
functionality, we drag from the AJAX Toolkit onto the ASPX form the
HoverMenuExtender. This will add references in your bin folder, and
also to the top of your ASPX page:

<%@ Register Assembly="AjaxControlToolkit"


Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit"
%>

Need help with Windows Dedicated Hosting? Try Server Intellect. I'm
a happy customer!

And our code should look something like this:

<form id="form1" runat="server">


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

<asp:Repeater ID="Repeater1" runat="server">


<ItemTemplate>
<asp:Panel ID="MenuPanel" runat="server"
Width="200px" BackColor="Beige"
BorderWidth="1px">
<asp:HyperLink ID="lnk_HyperLink1"
runat="server" NavigateUrl="#"
Text='<
%#DataBinder.Eval(Container.DataItem,
"MenuText")%>' />
</asp:Panel>
<asp:Panel ID="HoverPanel" runat="server">
<%#DataBinder.Eval(Container.DataItem,
"MenuInfo")%>
</asp:Panel>
<ajaxToolkit:HoverMenuExtender
ID="HoverMenuExtender1" runat="server"
TargetControlID="MenuPanel"
PopupControlID="HoverPanel"
PopupPosition="Right" PopDelay="10" />
</ItemTemplate>
</asp:Repeater>
</form>

Within our ItemTemplate of the Repeater, we add two Panels - one


for the menu item, and the other for the menu item description. We
specify each control ID in the HoverMenu Extender, which takes
care of the rest of the functionality for us.

This tutorial was created with and aimed toward users of Visual
Studio.NET 2008. 2005 can be used, but Microsoft's ASP.NET AJAX
Extensions, which can be downloaded at this location, must be
installed.
Also, if using VS.NET 2005, some additional steps may be required
that are not listed in this article.

Microsoft have a Control Toolkit that is not included with the .NET
Framework, but can be downloaded from
www.codeplex.com/AjaxControlToolkit. This Toolkit is constantly
being updated and consists mainly of AJAX Extenders for existing
ASP.NET Controls.
By now, you are bound to have seen Google's implementation of the
AutoComplete AJAX control for commonly searched terms. The
Google search box will now offer you commonly searched for
phrases as you type! This means that the form will guess what you
are typing, and provide matches for you to choose.

We used over 10 web hosting companies before we found Server


Intellect. Their dedicated servers and add-ons were setup swiftly, in
less than 24 hours. We were able to confirm our order over the
phone. They respond to our inquiries within an hour. Server
Intellect's customer support and assistance are the best we've ever
experienced.

In this tutorial, you will learn how to implement something similar


using the AutoComplete AJAX Control and a Web Method.
We will be using a SQL database to match the typed text against
and retrieve matches to the user.

We start by creating the database. Open up a new VB.NET web


application project in Visual Studio, then right-click the App_Data
folder in Solution Explorer and choose Add New Item.. SQL Server
Database. We will create one table with two columns - id, name. We
will create a database of names. For this example, it will not be a
comprehensive list of names, but we will add some sample data
once we have designed the table.
We set the id to data type int, and name to data type varchar(50).
We also set the id column as Primary Key and Identity Specification,
then save the table and close.

Next, right-click the project in Solution Explorer and choose Add


ASP.NET Folder > App_Code. Then right-click the App_Code folder
and Add New Item.. LINQ to SQL Classes. We will create a class to
represent our database table so that we can use LINQ to retrieve
records from our database as we type.
We should be presented with the Object Relation Designer. Here, we
can goto Server Explorer and drag our table to the design view, then
save. This will allow VS to create the class representation for us. We
will then use LINQ to interact with this class and then save the
changes back to the database.

Next, we will build our Web Method in the back-end of our ASPX
page. Let's start by making sure we are referencing the LINQ
namespace:

Imports System.Linq

If you're ever in the market for some great Windows web hosting,
try Server Intellect. We have been very pleased with their services
and most importantly, technical support.

We can then create our Web Method like so:

<System.Web.Services.WebMethod()> _
Public Shared Function GetNames(ByVal prefixText As
String, ByVal count As Integer) As String()
Dim db As New NamesDataContext()
Return db.tblNames.Where(Function(n)
n.name.StartsWith(prefixText)).OrderBy(Function(n)
n.name).Select(Function(n)
n.name).Take(count).ToArray()
End Function

If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

Here we are creating a Web Method within the page. We could


create this as a Web Service, but for this example we are only using
it on this page.
We first instantiate our LINQ to SQL Class we created earlier, then
we use Lambda Expressions to select data from the database that
match what the user is typing in. This method will be called from the
AJAX AutoComplete Extender when the user types into the textbox.
The AJAX Extender will maange the calling of the method, and also
the retrieval of the string array.

We will also have a button that will move the chosen suggested text
to a label:

Protected Sub butName_Click(ByVal sender As Object, ByVal


e As System.EventArgs) Handles butName.Click
lblChosenName.Text = "You chose the name " &
txtName.Text & "."
End Sub

We are using Server Intellect and have found that by far, they are
the most friendly, responsive, and knowledgeable support team
we've ever dealt with!

Our entire code-behind will look something like this:

Imports System.Linq

Partial Class _Default


Inherits System.Web.UI.Page

<System.Web.Services.WebMethod()> _
Public Shared Function GetNames(ByVal prefixText As
String, ByVal count As Integer) As String()
Dim db As New NamesDataContext()
Return db.tblNames.Where(Function(n)
n.name.StartsWith(prefixText)).OrderBy(Function(n)
n.name).Select(Function(n)
n.name).Take(count).ToArray()
End Function

Protected Sub butName_Click(ByVal sender As Object,


ByVal e As System.EventArgs) Handles butName.Click
lblChosenName.Text = "You chose the name " &
txtName.Text & "."
End Sub
End Class

Now we have built our Web Method, we will implement it into our
ASPX page. We will first add the following ASP.NET Controls: a
TextBox, Button and Label. Also make sure there is a ScriptManager,
and an UpdatePanel if you want the form to make use of
Asynchronus Postbacks.

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server">


<ContentTemplate>
Name:
<asp:TextBox ID="txtName" runat="server" />
<br />
<asp:Button ID="butName" runat="server" Text="Go"
onclick="butName_Click" /><br />
<br />
<asp:Label ID="lblChosenName" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

Server Intellect assists companies of all sizes with their hosting


needs by offering fully configured server solutions coupled with
proactive server management services. Server Intellect specializes
in providing complete internet-ready server solutions backed by
their expert 24/365 proactive support team.

Now if we go into Design view of our ASPX page, we can click on the
SmartTag of the TextBox and choose Add Extender. This will only be
available if we have the AJAX Toolkit installed.
Once you choose to Add Extender, you can choose the
AutoComplete option. This will add a Custom Control to the page,
named AutoCompleteExtender. We need to set the ServiceMethod
attribute to the name of our Web Method, and also set the
TargetControlID to that of the TextBox we will be using. Setting
AutoComplete=Off on the textbox will turn off the built-in
autocomplete in IE and FireFox.

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server">


<ContentTemplate>
Name:
<asp:TextBox ID="txtName" runat="server"
AutoComplete="Off" />
<cc1:AutoCompleteExtender
ID="txtName_AutoCompleteExtender" runat="server"
TargetControlID="txtName"
MinimumPrefixLength="1"
ServiceMethod="GetNames">
</cc1:AutoCompleteExtender>
<br />
<asp:Button ID="butName" runat="server" Text="Go"
onclick="butName_Click" /><br />
<br />
<asp:Label ID="lblChosenName" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

The AutoComplete Extender is also smart enough to provide caching


- it will detect if the search term has been previously entered, and if
so, it will not need to make another call to the database; it will
retrieve results from cache.

This tutorial was created with and aimed toward users of Visual
Studio.NET 2008. 2005 can be used, but Microsoft's ASP.NET AJAX
Extensions, which can be downloaded at this location, must be
installed.
Also, if using 2005, some additional steps may be required that are
not listed in this article.

Microsoft have a Control Toolkit that is not included with the .NET
Framework, but can be downloaded from
www.codeplex.com/AjaxControlToolkit. This Toolkit is constantly
being updated and consists mainly of AJAX Extenders for existing
ASP.NET Controls.
By now, you are bound to have seen Google's implementation of the
AutoComplete AJAX control for commonly searched terms. The
Google search box will now offer you commonly searched for
phrases as you type! This means that the form will guess what you
are typing, and provide matches for you to choose.

Try Server Intellect for Windows Server Hosting. Quality and


Quantity!

In this tutorial, you will learn how to implement something similar


using the AutoComplete AJAX Control and a Web Method.
We will be using a SQL database to match the typed text against
and retrieve matches to the user.

We start by creating the database. Open up a new C# web


application project in Visual Studio, then right-click the App_Data
folder in Solution Explorer and choose Add New Item.. SQL Server
Database. We will create one table with two columns - id, name. We
will create a database of names. For this example, it will not be a
comprehensive list of names, but we will add some sample data
once we have designed the table.
We set the id to data type int, and name to data type varchar(50).
We also set the id column as Primary Key and Identity Specification,
then save the table and close.

Next, right-click the project in Solution Explorer and choose Add


ASP.NET Folder > App_Code. Then right-click the App_Code folder
and Add New Item.. LINQ to SQL Classes. We will create a class to
represent our database table so that we can use LINQ to retrieve
records from our database as we type.
We should be presented with the Object Relation Designer. Here, we
can goto Server Explorer and drag our table to the design view, then
save. This will allow VS to create the class representation for us. We
will then use LINQ to interact with this class and then save the
changes back to the database.

Next, we will build our Web Method in the back-end of our ASPX
page. Let's start by making sure we are referencing the LINQ
namespace:

using System.Linq;

If you're ever in the market for some great Windows web hosting,
try Server Intellect. We have been very pleased with their services
and most importantly, technical support.

We can then create our Web Method like so:

[System.Web.Services.WebMethod]
public static string[] GetNames(string prefixText, int count)
{
NamesDataContext db = new NamesDataContext();
return db.tblNames.Where(n=>
n.name.StartsWith(prefixText)).OrderBy(n =>
n.name).Select(n => n.name).Take(count).ToArray();
}

We chose Server Intellect for its dedicated servers, for our web
hosting. They have managed to handle virtually everything for us,
from start to finish. And their customer service is stellar.

Here we are creating a Web Method within the page. We could


create this as a Web Service, but for this example we are only using
it on this page.
We first instantiate our LINQ to SQL Class we created earlier, then
we use Lambda Expressions to select data from the database that
match what the user is typing in. This method will be called from the
AJAX AutoComplete Extender when the user types into the textbox.
The AJAX Extender will maange the calling of the method, and also
the retrieval of the string array.

We will also have a button that will move the chosen suggested text
to a label:

protected void butName_Click(object sender, EventArgs e)


{
lblChosenName.Text = "You chose the name " +
txtName.Text + ".";
}

We moved our web sites to Server Intellect and have found them to
be incredibly professional. Their setup is very easy and we were up
and running in no time.

Our entire code-behind will look something like this:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

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


{
protected void Page_Load(object sender, EventArgs e)
{

[System.Web.Services.WebMethod]
public static string[] GetNames(string prefixText, int
count)
{
NamesDataContext db = new NamesDataContext();
return db.tblNames.Where(n=>
n.name.StartsWith(prefixText)).OrderBy(n =>
n.name).Select(n => n.name).Take(count).ToArray();
}

protected void butName_Click(object sender, EventArgs


e)
{
lblChosenName.Text = "You chose the name " +
txtName.Text + ".";
}
}

Now we have built our Web Method, we will implement it into our
ASPX page. We will first add the following ASP.NET Controls: a
TextBox, Button and Label. Also make sure there is a ScriptManager,
and an UpdatePanel if you want the form to make use of
Asynchronus Postbacks.

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server">


<ContentTemplate>
Name:
<asp:TextBox ID="txtName" runat="server" />
<br />
<asp:Button ID="butName" runat="server" Text="Go"
onclick="butName_Click" /><br />
<br />
<asp:Label ID="lblChosenName" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

Try Server Intellect for Windows Server Hosting. Quality and


Quantity!

Now if we go into Design view of our ASPX page, we can click on the
SmartTag of the TextBox and choose Add Extender. This will only be
available if we have the AJAX Toolkit installed.
Once you choose to Add Extender, you can choose the
AutoComplete option. This will add a Custom Control to the page,
named AutoCompleteExtender. We need to set the ServiceMethod
attribute to the name of our Web Method, and also set the
TargetControlID to that of the TextBox we will be using. Setting
AutoComplete=Off on the textbox will turn off the built-in
autocomplete in IE and FireFox.

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UP1" runat="server">


<ContentTemplate>
Name:
<asp:TextBox ID="txtName" runat="server"
AutoComplete="Off" />

<cc1:AutoCompleteExtender
ID="txtName_AutoCompleteExtender" runat="server"
TargetControlID="txtName"
MinimumPrefixLength="1"
ServiceMethod="GetNames">
</cc1:AutoCompleteExtender>
<br />
<asp:Button ID="butName" runat="server" Text="Go"
onclick="butName_Click" /><br />
<br />
<asp:Label ID="lblChosenName" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

The AutoComplete Extender is also smart enough to provide caching


- it will detect if the search term has been previously entered, and if
so, it will not need to make another call to the database; it will
retrieve results from cache.

This tutorial was created with Visual Studio.NET 2008. 2005 can be
used, but Microsoft's ASP.NET AJAX Extensions, which can be
downloaded at this location, must be installed.

Microsoft have a Control Toolkit that is not included with the .NET
Framework, but can be downloaded from
www.codeplex.com/AjaxControlToolkit. This Toolkit is constantly
being updated and consists mainly of AJAX Extenders for ASP.NET
Controls.
In this tutorial, we will be looking at one of these extenders to
create a Password Strength indicator, which extends an ASP.NET
TextBox, and also the AJAX Accordion.

Try Server Intellect for Windows Server Hosting. Quality and


Quantity!

To get started, we need to first download the AJAX Control Toolkit


from Microsoft, using the link above. We should get the ZIP file with
the source code.
Once downloaded, extract to a folder on your computer and start
Visual Studio. We will add the toolkit to the toolbox within VS. Open
up the toolkit and right-click in an empty space, then choose Add
Tab. Give it a name like AJAX Toolkit, or AJAX Extenders. Then when
it is added, right-click under the tab and select Choose Items. Wait
for the Window to appear, and then click the Browse button
under .NET Framework Components. Navigate to the folder you
extracted to and select the AjaxControlToolkit.dll in the
SampleWebSite/Bin/ directory. VS will then add all the AJAX Toolkit
controls to the toolbox.

Now we are able to add any of these controls to our web


applications. We must still remember the ScriptManager, as all of
these controls are AJAX-enabled. So to start, let's add the
ScriptManager control:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"
runat="server" />
</form>

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

Next, we will add a textbox control to the page:

<form id="form1" runat="server">


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

Password: <asp:TextBox ID="TextBox1" runat="server"


TextMode="Password" /><br />

</form>

If you're looking for a really good web host, try Server Intellect - we
found the setup procedure and control panel, very easy to adapt to
and their IT team is awesome!

Now if we go into the design view of our ASPX page, we will see that
clicking on the Smart Tag of the textbox control gives us a new
option - Add Extender. Clicking on this will provide us with a number
of different extender controls within the AJAX Toolkit that we can
apply to this textbox. Choose PasswordStrength Extender, hit Ok,
and repeat to also add the DropShadow Extender.

<form id="form1" runat="server">


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

Password: <asp:TextBox ID="TextBox1" runat="server"


TextMode="Password" /><br />
<cc1:PasswordStrength
ID="TextBox1_PasswordStrength" runat="server"
Enabled="True" TargetControlID="TextBox1">
</cc1:PasswordStrength>
<cc1:DropShadowExtender
ID="TextBox1_DropShadowExtender" runat="server"
Enabled="True" TargetControlID="TextBox1">
</cc1:DropShadowExtender>
</form>

If you're ever in the market for some great Windows web hosting,
try Server Intellect. We have been very pleased with their services
and most importantly, technical support.
As usual, VS does a lot of the work for us, especially behind the
scenes. Because these are essentially custom controls, they are
already fully functional. All we need to do is add them to our project
and reference which control will be being extended. Of course, there
are further attribtues to customize, for example, we can modify the
DropShadow's Opacity and Radius, etc. And we can also create our
own CSS classes to completely change the look of the controls.

If we ran the web application right now, we would be presented with


a textbox with a drop shadow. Only when we begin typing in the
textbox, we see the PasswordStrength Extender appear, notifying us
of the strength of our password, based upon number of characters.
Finally, let's look at a popular control of the AJAX Toolkit, which is
not an Extender, the Accordion. This is a group of panels, of which
the headers can be clicked to reveal and hide the contents. This is a
great space-saver on a web page and also a nice-looking effect.
Drag the Accordion from the toolkit onto the ASPX page, and a few
Accordion Panels:

<cc1:Accordion ID="Accordion1" runat="server"


RequireOpenedPane="false">
<Panes>
<cc1:AccordionPane ID="AccPane1" runat="server">
<Header>This is Pane 1.</Header>
<Content><br />This is pane one
content.</Content>
</cc1:AccordionPane>
<cc1:AccordionPane ID="AccPane2" runat="server">
<Header>This is Pane 2.</Header>
<Content><br />This is pane two
content.</Content>
</cc1:AccordionPane>
<cc1:AccordionPane ID="AccPane3" runat="server">
<Header>This is Pane 3.</Header>
<Content><br />This is pane three
content.</Content>
</cc1:AccordionPane>
</Panes>
</cc1:Accordion>

We migrated our web sites to Server Intellect over one weekend and
the setup was so smooth that we were up and running right away.
They assisted us with everything we needed to do for all of our
applications. With Server Intellect's help, we were able to avoid any
headaches!

By default, this control will have one pane open at all times,
meaning you cannot close all of them. This can be changed by
setting the RequireOpenPane attribute to false, as in our example.
This allows all panes to be closed to save even more room.
The entire ASPX page will look something like this:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register assembly="AjaxControlToolkit"


namespace="AjaxControlToolkit" tagprefix="cc1" %>

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


Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Using the AJAX Control Toolkit in ASP.NET
3.5</title>
</head>
<body>

<form id="form1" runat="server">

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

Password: <asp:TextBox ID="TextBox1"


runat="server" TextMode="Password" /><br />
<cc1:PasswordStrength
ID="TextBox1_PasswordStrength" runat="server"
Enabled="True" TargetControlID="TextBox1">
</cc1:PasswordStrength>
<cc1:DropShadowExtender
ID="TextBox1_DropShadowExtender" runat="server"
Enabled="True" TargetControlID="TextBox1">
</cc1:DropShadowExtender>
<br />
<br />
<cc1:Accordion ID="Accordion1" runat="server"
RequireOpenedPane="false">
<Panes>
<cc1:AccordionPane ID="AccPane1"
runat="server">
<Header>This is Pane 1.</Header>
<Content><br />This is pane one
content.</Content>
</cc1:AccordionPane>
<cc1:AccordionPane ID="AccPane2"
runat="server">
<Header>This is Pane 2.</Header>
<Content><br />This is pane two
content.</Content>
</cc1:AccordionPane>
<cc1:AccordionPane ID="AccPane3"
runat="server">
<Header>This is Pane 3.</Header>
<Content><br />This is pane three
content.</Content>
</cc1:AccordionPane>
</Panes>
</cc1:Accordion>
</form>

</body>
</html>

This tutorial was created with Visual Studio.NET 2008. 2005 can be
used, but Microsoft's ASP.NET AJAX Extensions, which can be
downloaded at this link, must be installed.

In AJAX, we can specify areas of a page to be refreshed without


refreshing the whole page. For this, we use UpdatePanels, which
also have the ability to make use of triggers. These triggers allow us
to specify which control initiates a certain postback. We can choose
to initiate a partial postback, or a full one.

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

In this example, we will look at how we can specify different controls


to refresh the whole page, and parts of the page. We will create two
UpdatePanels and see how we can refresh each of them as well as
refresh the whole page with the triggers.

First, we will start off by adding the ScriptManager, if it's not already
there, like so:

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

This will handle all of our AJAX calls for us, which makes it a lot
easier to develop AJAX applications.
Next, we add the UpdatePanel controls:

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>
<asp:Label ID="lblTime2" runat="server" /><br />
<asp:Button ID="butTime2" runat="server"
Text="Refresh Page" /><br />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:UpdatePanel ID="UpdatePanel2" runat="server">

<ContentTemplate>
<asp:Label ID="lblTime3" runat="server" /><br />
</ContentTemplate>
</asp:UpdatePanel>
</form>

Server Intellect assists companies of all sizes with their hosting


needs by offering fully configured server solutions coupled with
proactive server management services. Server Intellect specializes
in providing complete internet-ready server solutions backed by
their expert 24/365 proactive support team.

Each UpdatePanel has its own ContentTemplate, which is the area


that will be refreshed upon an Asynchronous postback. We have
included a label in each content, and will use the code-behind to
display the current time. This will allow us to easily see what area of
the page is being refreshed - we will also put a label and a button
outside of the UpdatePanels so that we can see when the whole
page is being refreshed - independent from the Panels.

We will use the button outside of the UpdatePanel to refresh the


panel, and the button within the UpdatePanel to refresh the whole
page. By default, a postback called within an UpdatePanel will be
hijacked by AJAX. Using triggers, we can have more control.
We add another label and a button:

<form id="form1" runat="server">


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

<asp:Label ID="lblTime1" runat="server" /><br />


<asp:Button ID="butTime1" runat="server"
Text="Refresh Panel" /><br /><br />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>
<asp:Label ID="lblTime2" runat="server" /><br />
<asp:Button ID="butTime2" runat="server"
Text="Refresh Page" /><br />
</ContentTemplate>
</asp:UpdatePanel>
<br />

<asp:UpdatePanel ID="UpdatePanel2" runat="server">

<ContentTemplate>
<asp:Label ID="lblTime3" runat="server" /><br />
</ContentTemplate>
</asp:UpdatePanel>
</form>

If you're ever in the market for some great Windows web hosting,
try Server Intellect. We have been very pleased with their services
and most importantly, technical support.

Now that we have a label and button on our page, and also in each
UpdatePanel, we will add the code-behind:

protected void Page_Load(object sender, EventArgs e)


{
lblTime1.Text = DateTime.Now.ToString("T");
lblTime2.Text = DateTime.Now.ToString("T");
lblTime3.Text = DateTime.Now.ToString("T");
}

We chose Server Intellect for its dedicated servers, for our web
hosting. They have managed to handle virtually everything for us,
from start to finish. And their customer service is stellar.

This simply sets the current time to the labels we created when the
page is loaded. This will also run when a partial postback is
performed.

Buttons are not the only control we can use for triggers. We will also
add a DropDownList:

<form id="form1" runat="server">


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

<asp:Label ID="lblTime1" runat="server" /><br />


<asp:Button ID="butTime1" runat="server"
Text="Refresh Panel" /><br /><br />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>
<asp:Label ID="lblTime2" runat="server" /><br />
<asp:Button ID="butTime2" runat="server"
Text="Refresh Page" /><br />
</ContentTemplate>
</asp:UpdatePanel>
<br />

<asp:UpdatePanel ID="UpdatePanel2" runat="server">

<ContentTemplate>
<asp:Label ID="lblTime3" runat="server" /><br />
</ContentTemplate>
</asp:UpdatePanel>
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="true">
<asp:ListItem>Change</asp:ListItem>
<asp:ListItem>My</asp:ListItem>
<asp:ListItem>Value</asp:ListItem>
</asp:DropDownList>
</form>

Finally, we can add the triggers. We will use the button outside of
the UpdatePanels to reload them, and the button inside the first
Panel will reload the page. The DropDownList will reload the Panels:

<Triggers>
<asp:AsyncPostBackTrigger ControlID="butTime1"
EventName="Click" />
<asp:PostBackTrigger ControlID="butTime2" />
</Triggers>
..
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1"
EventName="SelectedIndexChanged" />
</Triggers>

Need help with Windows Dedicated Hosting? Try Server Intellect. I'm
a happy customer!

The ASPX page will now look something like this:

<form id="form1" runat="server">


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

<asp:Label ID="lblTime1" runat="server" /><br />


<asp:Button ID="butTime1" runat="server"
Text="Refresh Panel" /><br /><br />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">


<Triggers>
<asp:AsyncPostBackTrigger ControlID="butTime1"
EventName="Click" />
<asp:PostBackTrigger ControlID="butTime2" />
</Triggers>

<ContentTemplate>
<asp:Label ID="lblTime2" runat="server" /><br />
<asp:Button ID="butTime2" runat="server"
Text="Refresh Page" /><br />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="DropDownList1"
EventName="SelectedIndexChanged" />
</Triggers>

<ContentTemplate>
<asp:Label ID="lblTime3" runat="server" /><br />
</ContentTemplate>
</asp:UpdatePanel>

<asp:DropDownList ID="DropDownList1" runat="server"


AutoPostBack="true">
<asp:ListItem>Change</asp:ListItem>
<asp:ListItem>My</asp:ListItem>
<asp:ListItem>Value</asp:ListItem>
</asp:DropDownList>
</form>

This tutorial was created with Visual Stuiod.NET 2008. It can be


recreated in 2005, but you will need to download and install
Microsoft's ASP.NET AJAX Extensions from this link.

AJAX and LINQ are two of the main focuses of Microsoft right now;
and no wonder - both have huge potential and power behind them.
In this example, we will show how we can use AJAX coupled with
LINQ and XML to create a Web Application that we can use to view
stored data instantaneously, as well as add to it in the same way.
AJAX provides the ease of use, by making the application run
smoothly and efficiently, as if it was a desktop application, while
LINQ provides the means to communicate and interact with the XML
file and data stored within.

We migrated our web sites to Server Intellect over one weekend and
the setup was so smooth that we were up and running right away.
They assisted us with everything we needed to do for all of our
applications. With Server Intellect's help, we were able to avoid any
headaches!

The first thing we need to do is create our XML file. For this
example, we will be using something like this:

<?xml version="1.0" encoding="utf-8"?>


<Persons>
<Person>
<Name>Paxton</Name>
<City>Munich</City>
<Age>29</Age>
</Person>
<Person>
<Name>Mike</Name>
<City>Orlando</City>
<Age>33</Age>
</Person>
</Persons>

We used over 10 web hosting companies before we found Server


Intellect. Their dedicated servers and add-ons were setup swiftly, in
less than 24 hours. We were able to confirm our order over the
phone. They respond to our inquiries within an hour. Server
Intellect's customer support and assistance are the best we've ever
experienced.

We will create a form to both read and write to the XML file: We will
need three textboxes and a button for additions, and then a button
and a textbox for reading. We will construct a form similar to this:

<form id="form1" runat="server">


<strong>Add to XML</strong><br />
Name:<br />
<asp:TextBox ID="txtName" runat="server" /><br />
City:<br />
<asp:TextBox ID="txtCity" runat="server" /><br />
Age:<br />
<asp:TextBox ID="txtAge" runat="server" /><br />
<asp:Button ID="butAdd" runat="server" Text="Add"
onclick="butAdd_Click" /><br />
<asp:Label ID="lblStatus" runat="server" />
<br /><br />
<strong>Read XML:</strong><br />
<asp:Button ID="butRead" runat="server" Text="Read"
onclick="butRead_Click" /><br />
<asp:TextBox ID="txtResults" runat="server"
Columns="25" Rows="10"
TextMode="MultiLine" />
</form>

Notice that our buttons have the OnClick handlers pointing to a


method. We will get to those in a minute, but first, let's finish off our
ASPX page. The only thing left to do is enable AJAX on this page. We
do this by adding a ScriptManager and an UpdatePanel, like so:

<form id="form1" runat="server">


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

<asp:UpdatePanel ID="updAdd" runat="server">


<Triggers>
<asp:AsyncPostBackTrigger ControlID="butAdd"
EventName="Click" />
</Triggers>
<ContentTemplate>
<strong>Add to XML</strong><br />
Name:<br />
<asp:TextBox ID="txtName" runat="server" /><br />
City:<br />
<asp:TextBox ID="txtCity" runat="server" /><br />
Age:<br />
<asp:TextBox ID="txtAge" runat="server" /><br />
<asp:Button ID="butAdd" runat="server" Text="Add"
onclick="butAdd_Click" /><br />
<asp:Label ID="lblStatus" runat="server" />
<br /><br />
<strong>Read XML:</strong><br />
<asp:Button ID="butRead" runat="server"
Text="Read" onclick="butRead_Click" /><br />
<asp:TextBox ID="txtResults" runat="server"
Columns="25" Rows="10"
TextMode="MultiLine" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

If you're ever in the market for some great Windows web hosting,
try Server Intellect. We have been very pleased with their services
and most importantly, technical support.

Before we start coding, we should make sure we have the correct


namespaces. We will be making use of LINQ to XML, so we need
System.Xml.Linq.
Our directives will look something like this:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

Now back to the buttons. We already added our handlers to the


buttons, so we're now done with the ASPX page and now we can
code our methods. We will create a method for the reading of the
XML file, as we are likely to use this more than once (other than just
on the button click - you'll see why). Our method will look something
like this:

protected void readXML()


{
XDocument xmlDoc =
XDocument.Load(Server.MapPath("People.xml"));

var persons = from person in


xmlDoc.Descendants("Person")
select new
{
Name = person.Element("Name").Value,
City = person.Element("City").Value,
Age = person.Element("Age").Value,
};

txtResults.Text = "";
foreach (var person in persons)
{
txtResults.Text = txtResults.Text + "Name: " +
person.Name + "\n";
txtResults.Text = txtResults.Text + "City: " +
person.City + "\n";
txtResults.Text = txtResults.Text + "Age: " +
person.Age + "\n\n";
}

if (txtResults.Text == "")
txtResults.Text = "No Results.";
}

Server Intellect assists companies of all sizes with their hosting


needs by offering fully configured server solutions coupled with
proactive server management services. Server Intellect specializes
in providing complete internet-ready server solutions backed by
their expert 24/365 proactive support team.

This method makes use of LINQ to first connect with the XML file
and then make a selection of all the data within. Once selected, we
loop each 'record' and output to the textbox control.
We call this method from the button click event:

protected void butRead_Click(object sender, EventArgs e)


{
readXML();
lblStatus.Text = "";
}

Next up is adding to the XML file. This actually requires less code
than reading. We will code this directly into the button click event. It
will look something like this:

protected void butAdd_Click(object sender, EventArgs e)


{
try
{
XDocument xmlDoc =
XDocument.Load(Server.MapPath("People.xml"));

xmlDoc.Element("Persons").Add(new
XElement("Person", new XElement("Name",
txtName.Text),
new XElement("City", txtCity.Text), new
XElement("Age", txtAge.Text)));

xmlDoc.Save(Server.MapPath("People.xml"));
lblStatus.Text = "Data successfully added to XML
file.";
readXML();
}
catch
{
lblStatus.Text = "Sorry, unable to process request.
Please try again.";
}
}

I just signed up at Server Intellect and couldn't be more pleased


with my Windows Server! Check it out and see for yourself.

We use a try, catch to reduce the number of errors in processing.


Again, we are using LINQ to add data to the XML file - first we load
the file, and then we simply add a new element into the parent
element, referring back to our XML structure will be useful for
understanding.
The entire code-behind will look something like this:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

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


{
protected void Page_Load(object sender, EventArgs e)
{

protected void butRead_Click(object sender, EventArgs


e)
{
readXML();
lblStatus.Text = "";
}

protected void butAdd_Click(object sender, EventArgs e)


{
try
{
XDocument xmlDoc =
XDocument.Load(Server.MapPath("People.xml"));

xmlDoc.Element("Persons").Add(new
XElement("Person", new XElement("Name",
txtName.Text),
new XElement("City", txtCity.Text), new
XElement("Age", txtAge.Text)));

xmlDoc.Save(Server.MapPath("People.xml"));
lblStatus.Text = "Data successfully added to XML
file.";
readXML();
}
catch
{
lblStatus.Text = "Sorry, unable to process request.
Please try again.";
}
}

protected void readXML()


{
XDocument xmlDoc =
XDocument.Load(Server.MapPath("People.xml"));

var persons = from person in


xmlDoc.Descendants("Person")
select new
{
Name = person.Element("Name").Value,
City = person.Element("City").Value,
Age = person.Element("Age").Value,
};

txtResults.Text = "";
foreach (var person in persons)
{
txtResults.Text = txtResults.Text + "Name: " +
person.Name + "\n";
txtResults.Text = txtResults.Text + "City: " +
person.City + "\n";
txtResults.Text = txtResults.Text + "Age: " +
person.Age + "\n\n";
}

if (txtResults.Text == "")
txtResults.Text = "No Results.";
}
}

You might also like