Partager via


Walkthrough: Creating a Basic ASP.NET AJAX-enabled Web Part

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

This walkthrough describes the steps for creating a basic ASP.NET AJAX-enabled Web Part that you can add to your Web Part page. The example creates a SayHello Web Part that derives from the ASP.NET 2.0 WebPart Class (in the System.Web.UI.WebControls.WebParts Namespace in the ASP.NET Class Library) for use in a Windows SharePoint Services 3.0 Web site.

Note

For more information about ASP.NET Web Parts, see ASP.NET Web Parts Overview and Introducing Web Part Controls.

Prerequisites

Windows SharePoint Services 3.0

Visual Studio 2005

Step 1: Create a Web Part Project

To create an AJAX-enabled Web Part control, you start by creating a class library project in the class library in Visual Studio 2005.

To create an ASP.NET Web Part project in Visual Studio 2005

  1. Start Visual Studio 2005.

  2. On the File menu, point to New, and then click Project.

  3. In Project Types, under Visual Basic or C#, select Windows.

  4. In the Templates pane, select Class Library.

  5. Type Sample.SayHello as the project name.

Step 2: Rename the base class and add required namespaces

After you create the project, a blank class file is displayed. You can change the default class name of Class1 to easily identify your new Web Part. In a class library project, only a few namespaces are included. You need to add two required namespaces and references to their assemblies. You must also derive the base class from System.Web.UI.WebControls.WebParts.WebPart. Then, you must add two global variables to update the user interface (UI).

To add namespace references and shared UI components

  1. Rename the default class by selecting Class1.cs in Solution Explorer, right-click, click Rename, and type SayHelloWebPart as the file name.

  2. On the Project menu, click Add Reference.

  3. In the Add Reference dialog on the .NET tab, select System.Web.Extensions and click OK.

  4. Repeat steps 2 and 3 for the System.Web namespace.

  5. In the references area of the class file, add a reference to System.Web.UI.WebControls and create two private variables for the UI, as shown in the following code.

    using System;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    namespace Sample.SayHello
    {
       public class SayHelloWebPart : WebPart
       {
         private Label displayName;
         private TextBox inputName;
       }
    }
    
    Imports System
    Imports System.Text
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.WebControls.WebParts
    Public Class SayHelloWebPart
       Inherits WebPart
       Private displayName As Label
       Private inputName as TextBox
    End Class
    
  6. You have now created a basic structure for the Web Part.

Step 3: Override CreateChildControls and create a button event handler

After configuring the new class to act as a Web Part, you must override the CreateChildControls method to build the UI. You must also add a button handler to refresh the display data.

To override CreateChildControls and create a button event handler

  1. In the SayHelloWebPart.cs file, copy and paste the following code to override the CreateChildControls method

    protected override void CreateChildControls()
    {
       base.CreateChildControls();
    
       //Fix for the UpdatePanel postback behaviour.
       EnsurePanelFix();
    
       LinkButton sayHello = new LinkButton();
       UpdatePanel refreshName = new UpdatePanel();
       ScriptManager scriptHandler = new ScriptManager();
       displayName = new Label();
       inputName = new TextBox();
    
       //Set up control properties.
       this.displayName.ID = "displayName";
       this.displayName.Text = "Hello!";
       this.inputName.ID = "inputName";
       sayHello.ID = "sayHello";
       sayHello.Text = "Say Hello";
       scriptHandler.ID = "scriptHandler";
       refreshName.ID = "refreshName";
       refreshName.UpdateMode = UpdatePanelUpdateMode.Conditional;
       refreshName.ChildrenAsTriggers = true;
    
       //Add the EventHandler to the Button.
       sayHello.Click += new EventHandler(ClickHandler);
    
       //Add the user interface (UI) controls to the UpdatePanel.
       refreshName.ContentTemplateContainer.Controls.Add(this.inputName);
       refreshName.ContentTemplateContainer.Controls.Add(sayHello);
       refreshName.ContentTemplateContainer.Controls.Add(this.displayName);
    
       //The ScriptManager control must be added first.
       this.Controls.Add(scriptHandler);
       this.Controls.Add(refreshName);
    }
    
    Protected Overrides Sub CreateChildControls()
       MyBase.CreateChildControls()
    
       'Fix for the UpdatePanel postback behaviour.
       EnsurePanelFix()
    
       Dim sayHello As New LinkButton
       Dim refreshName As New UpdatePanel
       Dim scriptHandler As New ScriptManager
       displayName = New Label
       inputName = New TextBox
    
       'Set up control properties.
       Me.displayName.ID = "displayName"
       Me.displayName.Text = "Hello!"
       Me.inputName.ID = "inputName"
       sayHello.ID = "sayHello"
       sayHello.Text = "Say Hello"
       scriptHandler.ID = "scriptHandler"
       refreshName.ID = "refreshName"
       refreshName.UpdateMode = UpdatePanelUpdateMode.Conditional
       refreshName.ChildrenAsTriggers = True
    
         'Add the EventHandler to the Button.
       AddHandler sayHello.Click, _
         New EventHandler(AddressOf ClickHandler)
    
       'Add the user interface (UI) controsl to the UpdatePanel
    
       refreshName.ContentTemplateContainer.Controls.Add(Me.displayName)
       refreshName.ContentTemplateContainer.Controls.Add(Me.inputName)
       refreshName.ContentTemplateContainer.Controls.Add(sayHello)
    
       'The ScriptManager must be added first.
       Me.Controls.Add(scriptHandler)
       Me.Controls.Add(refreshName)
    End Sub
    
  2. Then, in the SayHelloWebPart.cs file, copy and paste the following code.

    private void ClickHandler(object sender, EventArgs args)
    {
       this.displayName.Text = "Hello, " 
         + this.inputName.Text.ToString() + ".";
    }
    
    Private Sub ClickHandler(ByVal sender As Object, _
                  ByVal args As EventArgs)
       Me.displayName.Text = "Hello, " & Me.inputName.Text & "!"
    End Sub
    
  3. Now you have created the basic UI and button handling event.

For ASP.NET controls that use the JavaScript _doPostBack() function to commit changes, a regular full-page postback event may occur even when the Web Part is inside an UpdatePanel control. Windows SharePoint Services 3.0 and ASP.NET AJAX cache certain form actions, which can cause a conflict between SharePoint and ASP.NET AJAX. To change this behavior, you must add code to scripts that are running in Windows SharePoint Services 3.0.

Step 4: Modify Windows SharePoint Services 3.0 scripts to change doPostBack() behavior

To modify scripts to ensure proper doPostBack() behavior

  1. In the SayHelloWebPart.cs file, copy and paste the following code.

    private void EnsurePanelFix()
    {
       if (this.Page.Form != null)
       {
         String fixupScript = @"
         _spBodyOnLoadFunctionNames.push(""_initFormActionAjax"");
         function _initFormActionAjax()
         {
           if (_spEscapedFormAction == document.forms[0].action)
           {
             document.forms[0]._initialAction = 
             document.forms[0].action;
           }
         }
         var RestoreToOriginalFormActionCore = 
           RestoreToOriginalFormAction;
         RestoreToOriginalFormAction = function()
         {
           if (_spOriginalFormAction != null)
           {
             RestoreToOriginalFormActionCore();
             document.forms[0]._initialAction = 
             document.forms[0].action;
           }
         }";
       ScriptManager.RegisterStartupScript(this, 
         typeof(SayHelloWebPart), "UpdatePanelFixup", 
         fixupScript, true);
       }
    }
    
    Private Sub EnsurePanelFix()
       If Me.Page.Form IsNot Nothing Then
         Dim fixupScript As New StringBuilder()
    
         With fixupScript
           .AppendLine("_spBodyOnLoadFunctionNames.push" & _
           "(""_initFormActionAjax"");")
           .AppendLine("function _initFormActionAjax()")
           .AppendLine("{")
           .AppendLine("if (_spEscapedFormAction == " & _
           "document.forms[0].action)")
           .AppendLine("{")
           .AppendLine("document.forms[0]._initialAction = " & _
           document.forms[0].action;")
           .AppendLine("}")
           .AppendLine("}")
           .AppendLine("var RestoreToOriginalFormActionCore = " & _
           RestoreToOriginalFormAction;")
           .AppendLine("RestoreToOriginalFormAction = function()")
           .AppendLine("{")
           .AppendLine("   if (_spOriginalFormAction != null)")
           .AppendLine("   {")
           .AppendLine("       RestoreToOriginalFormActionCore();")
           .AppendLine("       document.forms[0]._initialAction = " & _
           "document.forms[0].action;")
           .AppendLine("   }")
           .AppendLine("}")
         End With
         ScriptManager.RegisterStartupScript(Me, _
           GetType(SayHelloWebPart), "UpdatePanelFixup", _
           fixupScript.ToString(), True)
       End If
    End Sub
    
  2. Now you have modified the scripts to ensure proper postback handling.

After you have added all of your code to your Web Part project, you can build your sample Web Part and deploy it. For more information about deploying a Web Part, see Walkthrough: Creating a Basic Web Part.

See Also

Other Resources

Solutions and Web Part Packages