Friday, April 15, 2011

Simple AJAX Tutorial

As usual, we will use the good old "Hello, world!" as our very first example. We will begin with the code, and then we'll do a bit of explanation afterwards. If you haven't already done so, you should create a new ASP.NET website project in Visual Web Developer. The IDE will create a Default.aspx and Default.aspx.cs file for you, which will look just like any other ASP.NET enabled page. Let's add some AJAX to it:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title>Hello, world!</title>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="MainScriptManager" runat="server" />
        <asp:UpdatePanel ID="pnlHelloWorld" runat="server">
                <asp:Label runat="server" ID="lblHelloWorld" Text="Click the button!" />
                <br /><br />
                <asp:Button runat="server" ID="btnHelloWorld" OnClick="btnHelloWorld_Click" Text="Update label!" />
In the CodeBehind, there's nothing new except for this event which you should add:
protected void btnHelloWorld_Click(object sender, EventArgs e)
    lblHelloWorld.Text = "Hello, world - this is a fresh message from ASP.NET AJAX! The time right now is: " + DateTime.Now.ToLongTimeString();
In the markup part, we use two new things, when compared to regular ASP.NET: The ScriptManager control and the UpdatePanel control. The ScriptManager makes sure that the required ASP.NET AJAX files are included and that AJAX support is added, and has to be included on every page where you wish to use AJAX functionality. After the manager, we have one of the most used controls when working with AJAX, the UpdatePanel. This control allows you to wrap markup which you would like to allow to be partially updated, that is, updated without causing a real postback to the server. More about the UpdatePanel in a coming chapter. Besides those two controls, everything else is standard controls, with no modifications that would indicate alternate behavior.

Try running the example site, and click the button. The label will be updated with our usual Hello world text, and the current time. Try repeatedly clicking the button, and you will see the label get the current timestamp each time. Notice the wonderful absence of a blinking window and a running status bar - everything is done without updating anything but the label! We've just created our first AJAX enabled page


Post a Comment


2011 ·Code-Studio by yrus.