Friday, September 11, 2009

Using ASP.NET Ajax controls

Here is a simple tutorial of the simplest of the Ajax functions called the “Partial Page Update”, this shows how to use the built in Visual Studio 2008 controls.  You will see from this that there is no need to write any of that old JavaScript plumbing and how simple it is to implement. 

Setting up your project

Start a new Visual Studio Project called AjaxDemo.

image

Add two text boxes to your default.aspx page called TextBox1 and TextBox2. then add a button called “Button1” with the text “Press Me”, the code is shown below:

<form id="form1" runat="server">
<div>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><p />
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><p />
    <asp:Button ID="Button1" runat="server" Text="Press Me" />
</div>
</form>

Next on the code behind (default.aspx.cs) add the following code to the Page_Load function which populates the text boxes with the current time.

protected void Page_Load(object sender, EventArgs e)
{
    TextBox1.Text = DateTime.Now.ToLongTimeString();
    TextBox2.Text = DateTime.Now.ToLongTimeString();
}

Run the application and it should look like this:

image

Pressing the button will cause a refresh of the page and both fields to be updated.

Implementing the Partial Page Update Ajax commands

To allow for Ajax on your page you need to add a ScriptManager Control.  this should be placed on the page before any other controls are rendered.  I find putting in on the Master Page works best, that way you don’t have to worry about it later.

1) Drag the ScriptManager from the tools in Visual Studio onto the design or code surface.

image

2) Next you need to add an UpdatePanel around the controls you want to take part in the partial update.  In this case I’m going to wrap TextBox2 and Button1.  Again simply drag the item from the tool box to your design or code surface.  move your controls between the UpdatePanel tags and add a <ContentTemplate> tag around the controls.

image

The code should look something like this:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><p />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><p />
    <asp:Button ID="Button1" runat="server" Text="Press Me" />
    </ContentTemplate>
    </asp:UpdatePanel>
</div>
</form>

Now press Play on your solution to see it in action.

 image

Pressing the button now will cause the second textbox to become updated but not the first as it is outside the update panel.  Also there will be no full Post Back event for the page refresh.