Click here to Skip to main content
Email Password   helpLost your password?
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

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("  "));
    
                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.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralExcellent!
halpage
0:12 25 Jan '10  
This works like a charm Thumbs Up Thank u very much Mahdi.

Dinesh
Generaldeploying ajax enabled usercontrol webpart in sharepoint
jchappidi
2:11 23 Jan '09  
hi,

The arcticle is very nice,but my requirement is i have ajax enabled user control and created as a webpart and deploying same as like your arctile .The webpart is not loading means i have added in web.config and done total prcedure(adding tags in webpart and adding script manager)
While adding webpart in sharepoint site its saying simply Unknow error ..

Can you please give an idea where the problem wil be and any thing need to be done....

only the thing i changed is by using usercontrol i have created my requiement and added that usercontrol as a webpart ...

Regards

JagadeeshV
GeneralUnknown server tag 'asp:ScriptManager'
Member 4299288
19:16 15 Jul '08  
When I go to homepage of Sharepoint 2007, I get an error:
Unknown server tag 'asp:ScriptManager'

So, can you help me to resolve this problem?
GeneralAuthentication Issues with Ajax extensions that require web services
Eric Murray
16:14 28 May '08  
Nice post!

I recently tried creating an Ajax web part for MOSS 2007 using the SlideShowExtender control. This control requires a web service. I can create and host the web service in MOSS fine, but because our website is using Windows Authentication and requires authentication when trying to call the web service, I can't seem to get this thing to work. Have you dealt with this before -- any ideas?

Thanks,

Eric
GeneralThere are easier ways....
Doodie Woddy Doodlechips
15:12 11 Feb '08  
Ajax WebParts for SharePoint 2007 with Gaia 33 minute [Video]
GeneralDeploy web part
hatem75
4:22 21 Nov '07  
what the steps we need to deploay your web part to MOSS ?
GeneralUnknown server tag 'asp:ScriptManager'
dudin
23:11 17 Nov '07  
Hello,

I added to the master page:
<%@ Import Namespace="Microsoft.Web.Atlas" %>
Then I added:
<asp:ScriptManager runat="server" ID="ScriptManager1">
</asp:ScriptManager>

I get an error:
Unknown server tag 'asp:ScriptManager'

Note: I have a web project. I added Microsoft.Web.Atlas.dll as a reference,
then I add "ScriptManager" and it works perfectly.

Thank you.

GeneralNot able to add Controls to the webpart in MOSS 2007
manasa1623
6:21 31 Oct '07  
HI I am trying to create a webpart in MOSS 2007 using VS 2005, but i am not able to add the controls(Label,Button etc.) like the ones used in this article. Please suggest in this regard.

Thanks in Advance
Manasa

ManasaSmile

GeneralRe: Not able to add Controls to the webpart in MOSS 2007
M1gee
10:05 14 Nov '07  
Whats the error your getting? Please be more specific

mike
GeneralSoftware Install
tuhin76
6:54 2 Oct '07  
Do i need to install Visual Studio 2005 and sharepoint extension for Visual Studio to the server where it runs Sharepoint 2007? When i edit master page it can't recognize script manager and underline it red.
GeneralControls not displaying?
robbydownunder
7:37 29 Jul '07  
Mahdi,

Wonderful post! I am having an issue getting any controls to display within SharePoint. The web part builds and deploys just fine. Adding the web part to the page displays no errors but all I am seeing in the Chrome and the title of the web part. Any ideas? Did I miss something?

Thanks!
Robby
GeneralRe: Controls not displaying?
robbydownunder
7:48 29 Jul '07  
Nevermind...forgot I had an override on the Render() method...Sleepy

Great job!
GeneralRe: Controls not displaying?
Mahdi Abdulhamid
11:34 29 Jul '07  

Smile GOOD LUCK

Mahdi Abdulhamid
http://www.devexpert.net

GeneralScript controls may not be registered before PreRender
ShamusFu
12:14 27 Jul '07  
I have copied this verbatim. I keep getting 'Script controls may not be registered before PreRender' no matter what.

If I remove the updateprogress part, the rest works fine.

I also have very strange behaviour that when I perform my first call or action, the TITLE of the HTML disappears.

Strange. The part still works, just the title is gone.

Thanks for any comments.
GeneralRe: Script controls may not be registered before PreRender
Mahdi Abdulhamid
11:33 29 Jul '07  
Dear Shamus

I wish I could help, but I think there is something wrong with the "web.config" sections, also be sure you have included the Script Manager registration line in the right place in the right master page.


Thank you.

Mahdi Abdulhamid
http://www.devexpert.net

GeneralAJAX in a WebPart without UpdatePanel?
Mandalorian4
6:05 25 Jul '07  
Excellent article! I was missing the tweaks to the Web.Config file.
I have a particularly complex project and I have to put a focus on performance.
After reading this article http://msdn.microsoft.com/msdnmag/issues/07/06/WickedCode/[^]

I am trying to create several web parts that call PageMethods (see above article). I see how you implemented the ScriptManager into the .MASTER page, but I cannot get an instance of the SCriptManager to add a Service Item to it.

In order to call a PageMethod in the code behind page you must add a reference to the page in the Scriptmanager. Any ideas how I can add a service Item reference to the ScriptManager?

Thanks.


Chris.Burns
GeneralRe: AJAX in a WebPart without UpdatePanel?
Mahdi Abdulhamid
11:29 29 Jul '07  
Dear Chris,

I'm sorry for late, but i did not come across this approach.

Good luck

Mahdi Abdulhamid
http://www.devexpert.net

QuestionCreating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions
Jawad Munir
1:07 5 Jun '07  
Hi Dear
I want to create a basic web part Using Visual Studio 2005 Extensions and followed all the steps presented on http://msdn2.microsoft.com/en-us/library/aa973249.aspx#WSS3WebPartVSExten_AddlRes[^] and build the solution. The solution was build successfully. Unfortunatley when it deploys the webpart to my sharepoint site it generates the following error message.
Object Reference not set to an instance of an object

The documentation describes that we are only required to debug our web part project and no other settings are required.

Kindly reply

Jawad Munir

AnswerRe: Creating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions
Jawad Munir
3:21 5 Jun '07  
Sorry sorry... I have resolved the issue.

Jawad Munir

GeneralRe: Creating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions
Mahdi Abdulhamid
2:39 6 Jun '07  
OK,
Good Luck

Mahdi Abdulhamid
http://www.devexpert.net

GeneralRe: Creating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions
Jawad Munir
23:57 8 Jun '07  
Thanks...
Be Blessed

Jawad Munir

GeneralRe: Creating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions
jarretf
4:34 20 Jul '07  
Just out of curiosity, what was your solution? The same thing is happening to me! I'm sure I am overlooking something...

Thanks,
Jarret
Smile

JarretF

GeneralThanks
Kalzon1
7:53 22 May '07  
Just wanted to thank you for this submission. I had been looking all over trying to figure out how to programatically add a ProgressTemplate to an UpdateProgress. Your ProgessTemplate class helped me accomplish it.

Thank you.

Keith Longwell
GeneralRe: Thanks
Mahdi Abdulhamid
11:26 22 May '07  
Dear Keith,

Thank you for nice words, and you are welcome anytime.

Mahdi Abdulhamid
http://www.devexpert.net

GeneralExpecting AutoComplete
vivekthangaswamy
21:08 20 May '07  
Expecting AutoComplete WebPart...

Your article is something similar to http://sharepoint.microsoft.com/blogs/mike/Lists/Posts/Post.aspx?ID=3[^





Last Updated 13 May 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010