Click here to Skip to main content
12,356,154 members (66,086 online)
Click here to Skip to main content
Add your own
alternative version

Stats

136.5K views
545 downloads
56 bookmarked
Posted

Microsoft Office SharePoint 2007 and ASP.NET 2.0 AJAX 1.0 Web Part

, 13 May 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
A simple SharePoint 2007 web part to calculate two numbers which supports ASP.NET 2.0 AJAX 1.0
Screenshot - ajax.jpg

Introduction

This article describes how to build your first SharePoint 2007 Web part which supports ASP.NET 2.0 AJAX 1.0.

Software needed

  • SharePoint Portal Server 2007 (installed with site collection created on port: 80)
  • Visual Studio 2005
  • Visual Studio 2005 Extensions for SharePoint 2007
  • ASP.NET 2.0 AJAX 1.0

Using the code

First you need to configure your SharePoint Portal to support AJAX. To do this, it is better to open a new AJAX web site in Visual Studio to pick a copy from configuration sections in web.config, or you can copy from here, so let's start:

  1. Add the following part under: <configSections>
    <sectionGroup name="system.web.extensions" 
        type="System.Web.Configuration.SystemWebExtensionsSectionGroup, 
        System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35">
    
    <sectionGroup name="scripting" 
        type="System.Web.Configuration.ScriptingSectionGroup, 
        System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35">
    
          <section name="scriptResourceHandler" 
          type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, 
          System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
          PublicKeyToken=31bf3856ad364e35" requirePermission="false" 
          allowDefinition="MachineToApplication"/>
    
    <sectionGroup name="webServices" 
        type="System.Web.Configuration.ScriptingWebServicesSectionGroup, 
        System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35">
    
          <section name="jsonSerialization" 
          type="System.Web.Configuration.ScriptingJsonSerializationSection, 
          System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
          PublicKeyToken=31bf3856ad364e35" requirePermission="false" 
          allowDefinition="Everywhere" />
    
          <section name="profileService" 
          type="System.Web.Configuration.ScriptingProfileServiceSection, 
          System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
          PublicKeyToken=31bf3856ad364e35" requirePermission="false" 
          allowDefinition="MachineToApplication" />
    
    
          <section name="authenticationService" 
          type="System.Web.Configuration.ScriptingAuthenticationServiceSection,
          System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
          PublicKeyToken=31bf3856ad364e35" requirePermission="false" 
          allowDefinition="MachineToApplication" />
    
    </sectionGroup>
    </sectionGroup>
    </sectionGroup>
    
  2. Add the following part under: <pages>

    <controls>
            <add tagPrefix="asp" namespace="System.Web.UI" 
        assembly="System.Web.Extensions, Version=1.0.61025.0, 
        Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </controls>
    
  3. Add the following part under : <compilation><assemblies>

    <add assembly="System.Web.Extensions, Version=1.0.61025.0, 
        Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    
  4. Add the following part under: <httpHandlers>

    <add verb="*" path="*.asmx" validate="false" 
        type="System.Web.Script.Services.ScriptHandlerFactory, 
        System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35"/>
    
    <add verb="*" path="*_AppService.axd" validate="false" 
        type="System.Web.Script.Services.ScriptHandlerFactory, 
        System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35"/>
    
    <add verb="GET,HEAD" path="ScriptResource.axd" 
        type="System.Web.Handlers.ScriptResourceHandler, 
        System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35" validate="false"/> 
    
  5. Add the following part under: <httpModules>

    <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, 
        System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35"/>
    
  6. At the end of web.config add the following part under: <configuration>

    <system.web.extensions>
        <scripting>
          <webServices>
          <!-- Uncomment this line to enable the authentication service. 
        Include requireSSL="true" if appropriate. -->
          <!--
           <authenticationService enabled="true" requireSSL = "true|false"/>
          -->
          <!-- Uncomment these lines to enable the profile service. 
        To allow profile properties to be retrieved and 
        modified in ASP.NET AJAX applications, 
        you need to add each property name to the readAccessProperties 
        and writeAccessProperties attributes. -->
          <!--
          <profileService enabled="true"
                      readAccessProperties="propertyname1,propertyname2"
                      writeAccessProperties="propertyname1,propertyname2" />
          -->
          </webServices>
          <!--
          <scriptResourceHandler enableCompression="true" 
                    enableCaching="true" />
          -->
        </scripting>
      </system.web.extensions>
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <modules>
          <add name="ScriptModule" preCondition="integratedMode" 
        type="System.Web.Handlers.ScriptModule, System.Web.Extensions, 
        Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35"/>
        </modules>
     
       <handlers>
          <remove name="WebServiceHandlerFactory-Integrated" />
          <add name="ScriptHandlerFactory" verb="*" path="*.asmx" 
        preCondition="integratedMode"
          type="System.Web.Script.Services.ScriptHandlerFactory, 
        System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35"/>
    
          <add name="ScriptHandlerFactoryAppServices" 
        verb="*" path="*_AppService.axd" preCondition="integratedMode" 
        type="System.Web.Script.Services.ScriptHandlerFactory, 
        System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35"/>
    
          <add name="ScriptResource" preCondition="integratedMode" 
        verb="GET,HEAD" path="ScriptResource.axd" 
        type="System.Web.Handlers.ScriptResourceHandler, 
        System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35" />
        </handlers>
      </system.webServer>
    
  7. Before closing web.config we should add the AJAX controls dll to SharePoint Safe Controls, so copy the following part under: <SafeControls>

    <SafeControl Assembly="System.Web.Extensions, Version=1.0.61025.0, 
        Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
        Namespace="System.Web.UI" TypeName="*" Safe="True" />
    
  8. It is time to include the AJAX script Manager to the master page. In my case, I've included the script manager control in the default.master located in the following path: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\GLOBAL

    So, according to your portal template; locate the right master page file or you can open the master page from the SharePoint Designer under _catalogs folder. After you locate the master page file, open the file then put the following line inside the top of <form> tag.

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

    As shown below:

    <form runat="server" onsubmit="return _spFormOnSubmitWrapper();">
     <WebPartPages:SPWebPartManager id="m" runat="Server" />
     <asp:ScriptManager runat="server" ID="ScriptManager1">
     </asp:ScriptManager>
      <TABLE class="ms-main" CELLPADDING=0 CELLSPACING=0 BORDER=0 
        WIDTH="100%" HEIGHT="100%">
    
  9. Finally it is time to write our code. Open a new web part project from Visual Studio 2005, then add a reference of System.Web.Extensions to the project and write the following code to web part code file:

    Note: There is a SharePoint Script included for changing the form action which may stop the form submission, so I included the FixFormAction method which will reset the form action again

    using System;
    using System.Runtime.InteropServices;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Serialization;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.WebPartPages;
    
    namespace AjaxWebPart
    {
        [Guid("733ee261-6e34-49cf-ae29-e8aeb4df4563")]
        public class AjaxWebPart : System.Web.UI.WebControls.WebParts.WebPart
        {
            public AjaxWebPart()
            {
                this.ExportMode = WebPartExportMode.All;
            }
            // ASP.NET Controls declaration
            private Label label;
            private Label label2;
            private Label label3;
    
            private TextBox textBox1;
            private TextBox textBox2;
    
            // ASP.NET AJAX Controls declaration
            protected UpdatePanel udatePanel;
            protected UpdateProgress updateProgress;
    
            protected override void CreateChildControls()
            {
    
                base.CreateChildControls();
    
                // Fix Form Action 
                this.FixFormAction();
    
                udatePanel = new UpdatePanel();
                updateProgress = new UpdateProgress();
    
                udatePanel.ID = "_UpdatePanel";
                updateProgress.ID = "_UpdateProgress";
    
                //Create Update Progress Template
                string templateHTML = 
                "<div><img alt=
                \"Loading...\" src=\"/_layouts/images/loader.gif\"/>
                    Loading...</div>";
    
                updateProgress.ProgressTemplate = 
                new ProgressTemplate(templateHTML);
    
                updateProgress.AssociatedUpdatePanelID = udatePanel.ClientID;
                
                udatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
    
                this.Controls.Add(udatePanel);
                
                this.label = new Label();
                this.label2 = new Label();
                this.label3 = new Label();
    
                this.label.Text = "Enter 1st Number: ";
                this.label2.Text = "Enter 2nd Number: ";
               
                this.textBox1 = new TextBox();
                this.textBox1.ID = "TextBox1";
    
                this.textBox2 = new TextBox();
                this.textBox2.ID = "TextBox2";
    
               //Adding Controls
                udatePanel.ContentTemplateContainer.Controls.Add(this.label);
                udatePanel.ContentTemplateContainer.Controls.Add
                            (this.textBox1);
                udatePanel.ContentTemplateContainer.Controls.Add
                        (new LiteralControl("<br />"));
    
                udatePanel.ContentTemplateContainer.Controls.Add(this.label2);
                udatePanel.ContentTemplateContainer.Controls.Add
                                (this.textBox2);
    
                udatePanel.ContentTemplateContainer.Controls.Add
                        (new LiteralControl("<br /><br />"));
                
                Button button = new Button();
                button.Text = "Calculate";
    
                button.Click += new EventHandler(HandleButtonClick);
                udatePanel.ContentTemplateContainer.Controls.Add(button);
    
                udatePanel.ContentTemplateContainer.Controls.Add
                    (new LiteralControl("&nbsp;&nbsp;"));
    
                udatePanel.ContentTemplateContainer.Controls.Add(this.label3);
    
                udatePanel.ContentTemplateContainer.Controls.Add
                                (updateProgress);
            }
    
            private void HandleButtonClick(object sender, EventArgs eventArgs)
            {
                //Just wait to see the progress loader working
                System.Threading.Thread.Sleep(1000);
    
                this.label3.Text = Convert.ToString(int.Parse(textBox1.Text) 
                + int.Parse(textBox2.Text));
    
            }
    
            //Fixing Form Action
            private void FixFormAction ()
            {
                if (this.Page.Form != null)
                {
                    string formOnSubmitAtt = 
                this.Page.Form.Attributes["onsubmit"];
                    if(formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
                    {
                        this.Page.Form.Attributes["onsubmit"] = 
                        "_spFormOnSubmitWrapper();";
                    }
                }
                ScriptManager.RegisterStartupScript
            (this, typeof(AjaxWebPart), "UpdatePanelFixup",
            "_spOriginalFormAction = document.forms[0].action; 
            _spSuppressFormOnSubmitWrapper=true;", true);
            }
        }
    
        //Class for Building progress tempales
        public class ProgressTemplate : ITemplate
        {
            private string template;
    
            public ProgressTemplate(string temp)
            {
                template = temp;
            }
    
            public void InstantiateIn(Control container)
            {
                LiteralControl ltr = new LiteralControl(this.template);
                container.Controls.Add(ltr);
            }
        }
    }

Then build the solution and deploy the web part from Visual Studio to your portal. As you see, it is a simple web part to calculate the summation of two integers.

Be sure that Visual Studio has restarted your IIS and after that, browse the MOSS portal and Add AjaxWebPart from the web part gallery.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mahdi Abdulhamid
Web Developer
Saudi Arabia Saudi Arabia
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 32777609-Aug-11 0:02
memberMember 32777609-Aug-11 0:02 
QuestionPartial post back not happening Pin
partha_mca30-Dec-10 12:37
memberpartha_mca30-Dec-10 12:37 
GeneralExcellent! Pin
halpage24-Jan-10 23:12
memberhalpage24-Jan-10 23:12 
Generaldeploying ajax enabled usercontrol webpart in sharepoint Pin
jchappidi23-Jan-09 1:11
memberjchappidi23-Jan-09 1:11 
GeneralUnknown server tag 'asp:ScriptManager' Pin
Member 429928815-Jul-08 18:16
memberMember 429928815-Jul-08 18:16 
GeneralAuthentication Issues with Ajax extensions that require web services Pin
Eric Murray28-May-08 15:14
memberEric Murray28-May-08 15:14 
GeneralThere are easier ways.... Pin
Doodie Woddy Doodlechips11-Feb-08 14:12
memberDoodie Woddy Doodlechips11-Feb-08 14:12 
GeneralDeploy web part Pin
hatem7521-Nov-07 3:22
memberhatem7521-Nov-07 3:22 
GeneralUnknown server tag 'asp:ScriptManager' Pin
dudin17-Nov-07 22:11
memberdudin17-Nov-07 22:11 
GeneralNot able to add Controls to the webpart in MOSS 2007 Pin
manasa162331-Oct-07 5:21
membermanasa162331-Oct-07 5:21 
GeneralRe: Not able to add Controls to the webpart in MOSS 2007 Pin
M1gee14-Nov-07 9:05
memberM1gee14-Nov-07 9:05 
GeneralSoftware Install Pin
tuhin762-Oct-07 5:54
membertuhin762-Oct-07 5:54 
QuestionControls not displaying? Pin
robbydownunder29-Jul-07 6:37
memberrobbydownunder29-Jul-07 6:37 
AnswerRe: Controls not displaying? Pin
robbydownunder29-Jul-07 6:48
memberrobbydownunder29-Jul-07 6:48 
GeneralRe: Controls not displaying? Pin
Mahdi Abdulhamid29-Jul-07 10:34
memberMahdi Abdulhamid29-Jul-07 10:34 
GeneralScript controls may not be registered before PreRender Pin
ShamusFu27-Jul-07 11:14
memberShamusFu27-Jul-07 11:14 
GeneralRe: Script controls may not be registered before PreRender Pin
Mahdi Abdulhamid29-Jul-07 10:33
memberMahdi Abdulhamid29-Jul-07 10:33 
QuestionAJAX in a WebPart without UpdatePanel? Pin
Mandalorian425-Jul-07 5:05
memberMandalorian425-Jul-07 5:05 
AnswerRe: AJAX in a WebPart without UpdatePanel? Pin
Mahdi Abdulhamid29-Jul-07 10:29
memberMahdi Abdulhamid29-Jul-07 10:29 
QuestionCreating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions Pin
Jawad Munir5-Jun-07 0:07
memberJawad Munir5-Jun-07 0:07 
AnswerRe: Creating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions Pin
Jawad Munir5-Jun-07 2:21
memberJawad Munir5-Jun-07 2:21 
GeneralRe: Creating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions Pin
Mahdi Abdulhamid6-Jun-07 1:39
memberMahdi Abdulhamid6-Jun-07 1:39 
GeneralRe: Creating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions Pin
Jawad Munir8-Jun-07 22:57
memberJawad Munir8-Jun-07 22:57 
GeneralRe: Creating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions Pin
jarretf20-Jul-07 3:34
memberjarretf20-Jul-07 3:34 
GeneralThanks Pin
Kalzon122-May-07 6:53
memberKalzon122-May-07 6:53 
GeneralRe: Thanks Pin
Mahdi Abdulhamid22-May-07 10:26
memberMahdi Abdulhamid22-May-07 10:26 
GeneralRe: Thanks Pin
fastian133529-Aug-11 1:41
memberfastian133529-Aug-11 1:41 
GeneralExpecting AutoComplete Pin
vivekthangaswamy20-May-07 20:08
membervivekthangaswamy20-May-07 20:08 
GeneralRe: Expecting AutoComplete [modified] Pin
Mahdi Abdulhamid21-May-07 7:32
memberMahdi Abdulhamid21-May-07 7:32 
GeneralAjax WebPart partially works Pin
Zotkunc19-May-07 5:51
memberZotkunc19-May-07 5:51 
GeneralRe: Ajax WebPart partially works Pin
Mahdi Abdulhamid19-May-07 11:17
memberMahdi Abdulhamid19-May-07 11:17 
GeneralRe: Ajax WebPart partially works Pin
Zotkunc19-May-07 22:48
memberZotkunc19-May-07 22:48 
GeneralRe: Ajax WebPart partially works Pin
Mahdi Abdulhamid20-May-07 0:23
memberMahdi Abdulhamid20-May-07 0:23 
GeneralRe: Ajax WebPart partially works Pin
Zotkunc20-May-07 2:03
memberZotkunc20-May-07 2:03 
GeneralRe: Ajax WebPart partially works Pin
Mahdi Abdulhamid20-May-07 5:30
memberMahdi Abdulhamid20-May-07 5:30 
GeneralError when deploying webpart Pin
Burak Donbay17-May-07 21:07
memberBurak Donbay17-May-07 21:07 
GeneralRe: Error when deploying webpart Pin
Mahdi Abdulhamid18-May-07 4:18
memberMahdi Abdulhamid18-May-07 4:18 
GeneralRe: Error when deploying webpart Pin
Burak Donbay20-May-07 0:00
memberBurak Donbay20-May-07 0:00 
GeneralRe: Error when deploying webpart Pin
Mahdi Abdulhamid20-May-07 0:27
memberMahdi Abdulhamid20-May-07 0:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160621.1 | Last Updated 13 May 2007
Article Copyright 2007 by Mahdi Abdulhamid
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid