Microsoft Technology, .Net, BizTalk, Sharepoint & etc.

Liedong(Ken) Zheng, Senior SharePoint Developer at SIMPLOT

Create a Ajax WebPart for SharePoint

Posted by ken zheng on September 30, 2008

Today, I followed Abdulla’s example to create a Ajax Webpart. It works very well. One thing really struggle me is I add Web Extenstion 3.5 instead of 1.06.

First of all you need to add
· System.Web
· System.Web.Extensions (v1.06)
· System.Web.Extensions.Design (v1.06)
. Syste.Data

Modify the SharePoint Web.Config file. http://msdn.microsoft.com/en-us/library/bb861898.aspx
The below is the c# code

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Data;
using System.Data.SqlClient;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.ComponentModel;

namespace SharePointAjaxWebPart
{
    [Guid("579e8377-d57c-4b5e-98c1-1001c20301cc")]
    public class MyAjaxWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {

    private GridView _grdSearch;
    private TextBox _txtSearch;
    private Button _btnSearch;
    private Label _lblMsg;
    private UpdatePanel _updatePanel;
    private UpdateProgress _updateProgress;
    private static readonly object EventSubmitKey = new object();

    public MyAjaxWebPart()
    {
        this.ExportMode = WebPartExportMode.All;
    }

    [WebBrowsable(true), Personalizable(PersonalizationScope.Shared), Category("AbdHaq Property")]
    public string LoadingImageURL {
        get {
            object _obj = ViewState["LoadingImageURL"];
            if (_obj == null) {
                return string.Empty;
            }
            else {
                return (string)ViewState["LoadingImageURL"];
            }

        }
        set { ViewState["LoadingImageURL"] = value; }
    }
    public event EventHandler Submit {
        add { Events.AddHandler(EventSubmitKey, value); }
        remove { Events.RemoveHandler(EventSubmitKey, value); }
    }

    private void _btnSearch_Click(object source, EventArgs e)
    {

        _grdSearch.Visible = false;

        System.Threading.Thread.Sleep(1500);

        ////Create DataTable Structure
        DataTable Dtable = new DataTable("tmpTable");
        ////User_ID Col
        Dtable.Columns.Add("User_ID", typeof(int));
        Dtable.Columns["User_ID"].AutoIncrement = true;
        Dtable.Columns["User_ID"].AutoIncrementSeed = 1;
        ////User_Name Col
        Dtable.Columns.Add("User_Name", typeof(string));
        ////User_Department Col
        Dtable.Columns.Add("User_Department", typeof(string));

        DataRow dr = default(DataRow);

        dr = Dtable.NewRow();
        dr["User_Name"] = "Abdulla Abdelhaq";
        dr["User_Department"] = "Technical";
        Dtable.Rows.Add(dr);

        dr = Dtable.NewRow();
        dr["User_Name"] = "Noura Ahmad";
        dr["User_Department"] = "Technical";
        Dtable.Rows.Add(dr);

        dr = Dtable.NewRow();
        dr["User_Name"] = "Oday Mohammad";
        dr["User_Department"] = "Production";
        Dtable.Rows.Add(dr);

        string _searchFor = "%";

        if (_txtSearch.Text != string.Empty) {
            _searchFor = _txtSearch.Text;
        }

        DataView dtView = new DataView(Dtable);
        dtView.RowFilter = "User_Name LIKE '%'+'" + _searchFor + "'+'%'";

        if (dtView.Count > 0) {
            _grdSearch.Visible = true;
            _grdSearch.AutoGenerateColumns = true;
            _grdSearch.DataSource = dtView;
            _grdSearch.DataBind();
            _lblMsg.Text = string.Empty;
        }
        else {
            _lblMsg.Text = "<font color='red'>Sorry, No Data Found!.</font>";
            _grdSearch.Visible = false;
        }

    }

    protected override void CreateChildControls()
    {
        Controls.Clear();

        _updatePanel = new UpdatePanel();
        {
            _updatePanel.ID = "UpdatePanel1";
            _updatePanel.ChildrenAsTriggers = true;
            _updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
        }

        _updateProgress = new UpdateProgress();
        _updateProgress.ID = "UpdateProgress1";

        string _templateHTML = null;
        if (LoadingImageURL == string.Empty) {
            _templateHTML = "<span>Loading ...</span>";
        }
        else {
            _templateHTML = "<div><img alt='Loading...' src='" + LoadingImageURL.Trim() + "'/></div>";
        }

        _updateProgress.ProgressTemplate = new ProgressTemplate(_templateHTML);

        _updateProgress.AssociatedUpdatePanelID = _updatePanel.ClientID;

        this.Controls.Add(_updatePanel);

        _grdSearch = new GridView();
        _grdSearch.ID = "GrdSearch";

        _txtSearch = new TextBox();
        _txtSearch.ID = "txtSearch";

        _btnSearch = new Button();
        _btnSearch.Text = "Search";
        _btnSearch.ID = "BtnSearch";

        _lblMsg = new Label();
        _lblMsg.ID = "lblMsgError";

        _btnSearch.Click += _btnSearch_Click;

        _updatePanel.ContentTemplateContainer.Controls.Add(_txtSearch);
        _updatePanel.ContentTemplateContainer.Controls.Add(_btnSearch);
        _updatePanel.ContentTemplateContainer.Controls.Add(_grdSearch);
        _updatePanel.ContentTemplateContainer.Controls.Add(_lblMsg);
        _updatePanel.ContentTemplateContainer.Controls.Add(_updateProgress);

    }

    protected override void OnInit(EventArgs e)
    {

        base.OnInit(e);

        //get the existing ScriptManager if it exists on the page
        ScriptManager _AjaxManager = ScriptManager.GetCurrent(this.Page);
        if (_AjaxManager == null) {

            //create new ScriptManager and EnablePartialRendering
            _AjaxManager = new ScriptManager();
            _AjaxManager.EnablePartialRendering = true;

            //Fix problem with postbacks and form actions (DevDiv 55525)
            Page.ClientScript.RegisterStartupScript(this.GetType(), this.ID, "_spOriginalFormAction = document.forms[0].action;", true);

            //tag:"form" att:"onsubmit" val:"return _spFormOnSubmitWrapper()"
            //blocks async postbacks after the first one
            //not calling "_spFormOnSubmitWrapper()" breaks all postbacks
            //returning true all the time, somewhat defeats the purpose of the
            //_spFormOnSubmitWrapper() which is to block repetitive postbacks,
            //but it allows MS AJAX Extensions to work properly

            if ((this.Page.Form != null)) {
                string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
                if (!string.IsNullOrEmpty(formOnSubmitAtt) & formOnSubmitAtt == "return _spFormOnSubmitWrapper();") {
                    this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
                }
                //add the ScriptManager as the first control in the Page.Form
                this.Page.Form.Controls.AddAt(0, _AjaxManager);

            }
        }

    }

    protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
    {
        _updatePanel.RenderControl(writer);
    }
}
//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);
    }

}

}

The full tutorial is here

2 Responses to “Create a Ajax WebPart for SharePoint”

  1. [...] Maybe I can find the solution here. [...]

  2. JG Vimalan said

    Useful information. Thanks.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>