CJ

The circle of life – ** .Net – Training – MOSS **

  • Past Post

  • Vistor Locations

MOSS, AJAX and the AutoCompleteExtender

Posted by Clayton James on July 8, 2007

This article will look at utilising ASP.Net 2.0 AJAX inside WSS 3.0. This article is also based off some great work completed by Todd Bleeker in his book Developers Guide To Windows SharePoint Services 3.0.

To complete the code associated with this article you will need to install ASP.Net 2.0 AJAX Extensions and the ASP.Net 2.0 AJAX Control Toolkit as we will be utilising AJAX Extensions, namely the AutoCompleteExtender control.

The first thing you need to do is make your WSS site AJAX ready. This blog article from the SharePoint team takes you through the steps in completing this and also has a nice little web part example to test and make sure everything is working as it should be.

Ok, what we are going to demonstrate is creating an AutoComplete Web Part that provides users with the ability to filter a drop down list as they type in a text box. See image below. This will be a two step process, firstly creating a web service that is the data source for the drop down list, and secondly creating the AutoComplete Web Part. I must also point out that there is no difference between creating this Web Part in WSS 3.0 or any standard ASP.Net 2.0 application (which is what WSS is J).

Web Service

  1. Open VS.Net and choose ASP.Net AJAX Enabled Web Site template (if you don’t see this option then you need to install ASP.Net 2.0 AJAX)
  2. Ensure location is HTTP and enter a URL like http://localhost/WebServices.
  3. In Solution Explorer, right click the project name and add a new item. Choose Web Service from the templates window.
  4. Enter SimpleWebService for the name and uncheck the Select code in separate file checkbox.
  5. Decorate the class with the ScriptService to enable AJAX calls.

    [Microsoft.Web.Script.Services.ScriptService]
    public class SimpleWebService : System.Web.Services.WebService

  6. Create a WebMethod that will return a list of employees. The WebMethod must conform to the precise interface expected by the AutoComplete extender control which includes two arguments that must be named prefixText and count. The prefixText argument contains the letters typed by the end user and the count contains the maximum number of items returned.

    [WebMethod]

    [Microsoft.Web.Script.Services.Script]Method]

    public System.Collections.Generic.List<string> GetEmployees(string prefixText, int count)

    {

                    string[] employees = new string[]{

    “Adam Wells”,

    “James MacGuire”,

    “Jeff Phillps”,

    “Jemma Knowles”,

    “Mary Jullop”,

    “Mark Dent”};

    System.Collections.Generic.List<string> employeeList = new System.Collections.Generic.List<string>();

    Int i = 0;

    foreach(string employee in employees)

    {

                    //check if max number of employees has been reached

                    if(i == count)

                    {

                                    break;

    }

    else if(employee.ToLower().StartsWith(preficText.ToLower()))

    {

                    employeeList.Add(employee);

                    i++;

    }

    }

    return employeeList;

    }

    This WebMethod returns a string array containing the first and last name for employees. This example could easily be altered to return a result from a database.

  7. This ends the Web Service/WebMethod necessary for the AutoCompleteExtender control.

Ok, now for the Web Part.

  1. Open VS.Net and create a new Class Library project. Enter AJAXStyleWebParts for the name.
  2. Add a reference to the ASP.Net AJAX assembly (Microsoft.Web.Extension.dll), and to the toolkit assembly AjaxControlToolKit (the extender controls are not found in the core ASP.Net AJAX assembly and you will need to build the ToolKit solution that you downloaded previously at the beginning of the article).
  3. Add a new class called AutoCompleteWebPart : System.Web.UI.WebControls.WebParts.WebPart (and inherit WebPart class)
  4. Add declarations to the top of the class:using

    using System.Web;

    using System.Web.UI.WebControls;
    using AjaxControlToolkit;

  5. Override the CreateChildControls method
  6. protected override void CreateChildControls()

    {

                //establish a path to the web service

                string webServicePath = “http://localhost/WebServices/SimpleWebService.asmx”; 

                try

    {

    //TextBox label

    Literal textboxLabel = new Literal();

    textboxLabel.Text = “”Type the name of a Employee: “;

    this.Controls.Add(textboxLabel);

     

    //TextBox to extend with the AutoComplete AJAX behaviour. Note: this is a normal asp textbox

    TextBox textbox = new TextBox();

    textbox.Attributes.Add(“id”, “SelectEmployeeTextBox”);

    this.Controls.Add(textbox);

     

    //autocomplete AJAX behaviour

    AutoCompleteExtender autoComplete = new AutoCompleteExtender();

    autoComplete.MinimumPrefixLength = 1;

    autoComplete.ServicePath = webServicePath;

    autoComplete.ServiceMethod = “GetEmployees”;

    autoComplete.TargetControlID = “SelectEmployeeTextBox”;

    this.Controls.Add(autoComplete);

    }

    catch(Exception ex)

    {

                    Literal errMsg = new Literal();

                    errMsg.Text = ex.Message;

                    this.Controls.Add(errMsg);

    }

    }

  7. This ends our AutoComplete Web Part. Now all we have to do deploy to the web applications bin directory or GAC, add a safe control entry, recycle the app pool, add the Web Part to the gallery and then add to your WSS page.
  8. Type the letters “mar” in the textbox to see the Web Part in action.
  9. So, now you have AJAX’ed your WSS site, created a Web Part and implemented the AutoCompleteExtender control which I think provides great functionality for any WSS site.

26 Responses to “MOSS, AJAX and the AutoCompleteExtender”

  1. Hey CJ

    Neil Here whats your email address.

    cheers,

  2. Delay said

    hi.
    I have a problem with my autocomplete.
    I created a autocompleteExtender dynamic and this run is run only the page, but if i run my project don´t show the component.
    I called my page in Iframe.
    I build a other componets (eje. calendarExtender), and this componentes are visible when i run all the project
    thanks for your help

    TextBox txtNvo = new TextBox();
    txtNvo.ID = “txt” + i;
    txtNvo.CssClass = “componentes2”;
    txtNvo.Style.Add(“POSITION”, “absolute”);
    txtNvo.Style.Add(“TOP”, +intPosicion + “px”);
    txtNvo.Style.Add(“LEFT”, “200px”);
    txtNvo.Style.Add(“text-transform”, “uppercase”);
    txtNvo.Width = Unit.Pixel(170);
    txtNvo.AutoPostBack = false;
    txtNvo.Enabled = true;
    txtNvo.EnableTheming = true;
    txtNvo.EnableViewState = true;
    txtNvo.Attributes.Add(“autocomplete”,”off”);

    AutoCompleteExtender autoComplete = new AutoCompleteExtender();
    autoComplete.ID = “autoComplete” + i;
    autoComplete.MinimumPrefixLength = 1;
    autoComplete.CompletionInterval = 1000;
    autoComplete.CompletionSetCount = 10;
    autoComplete.ServicePath = “~/WS-autocomplete.asmx”;
    autoComplete.ServiceMethod = “getContribuyenteApellido”;
    autoComplete.TargetControlID =txtNvo.ID.ToString();
    autoComplete.BehaviorID = autoComplete.ID.ToString();
    autoComplete.Enabled = true;
    autoComplete.EnableClientState = true;
    autoComplete.EnableViewState = true;

    Page.FindControl(“form1”).Controls.Add(autoComplete);

  3. dhaval said

    I have impletemented and working fine as administrator. but It’s throwing error message for non admin user.
    did I miss somthing in configuration ?

  4. I am receiving Value cannot be null. Parameter name: child on the web part when applied in Sharepoint??

  5. Janaiah said

    i am getting the javascript error while entering the text in textbox. i am the administrator to my sharepoint site. i followed every step what you shown above but i am getting such javascript error. please help me in this as soon as possible.

  6. Vivek Panchal said

    Hi,
    I m using AJAX AutoTextExtender with WebService in Sharepoint Application. the problem is I am getting Permission Denied error while using this control in Internet Explorer 7(IE7) and blank in FireFox browser..
    Please let me know if anyone has solution…
    my id is yourfriendvivek@gmail.com
    –Vivek Panchal

  7. Chintan said

    Cool Stuff!

  8. William Mayvis said

    Hi,

    I have succesfully implemented the ajaxcontroltoolkit in WSS with features.
    Everything works fine. But one thing. The autocompletelistbox is not located under the autocomplete textbox, but on the top of the webpart.

    In the autocompleteextender examples, they works with animations tag inside autocompleteextender tag. I told, i create the extender in a webpart, so I don’t have a aspx page as html.

    Have someone of you a suggestion?
    That will be great.

    Thanks William

  9. Suresh said

    How can we retrieve from database without web services.can you tell me plz?

  10. Richard said

    This example is not fully documented. There is no mention of the requirement to add a script manager to the page to enable AJAX web parts in SharePoint, nor is there anything about the workaround/hack needed to be put in place to circumvent the _spFormOnSubmitWrapper() async postback problem on SharePoint web pages

    As it is, with that in place, I still can’t get the example working. I am getting an error message: “The TargetControlID of ” is not valid”. It appears that the autocomplete extender control is not picking up the textbox to use when referenced programatically

  11. Rakesh Laveti said

    Sorry guys, I forgot to place WebUserControl code(AutoExtenderControl.ascx)
    ——————————————————

    Type Name of Country:

  12. Rakesh Laveti said

    Actually, It is not copying to web

    In WebUserControl(AutoExtenderControl.ascx):
    ———————————————–
    1. Add new item and select WebUserControl
    2. uncheck place code in seperate file
    3. Import namespace System,System.Web,System.Web.UI,System.Web.UI.WebControls,AjaxControlToolkit using import directive
    4. Register assembly AjaxControlToolkit using Register directive
    5.Place the following controls
    a. ScriptmanagerProxy
    b.UpdatePanel
    c.In update Panel, Place AutoCompleteExtender
    d. One TextBox
    6.Give properties for AutoCompleteExtender
    ID=”AutoCompleteExtender1″ runat=”server” UseContextKey=”True”
    MinimumPrefixLength=”1″ ServicePath=”AutoExtenderWebService.asmx” ServiceMethod=”GetEmployees” TargetControlID=”TextBox1″

    Enjoy!!!!!

    • lili said

      question:
      1) the project is Class Library, how can I add an WebUserControl(AutoExtenderControl.ascx) to it?

      2) on the AutoExtenderControl.ascx, ServicePath=”AutoExtenderWebService.asmx” and on the CreateChildControls method webServicePath = “http://localhost/WebServices/SimpleWebService.asmx” is there a conflict?

  13. vikram said

    Thank u rakesh it is working..

  14. yutianyi said

    As Rakesh Laveti said, I create a WebUserControl, if the page has no up-down scroll, the AutoExtenderControl work good, but if the page has up-down scroll, the popup list is displayed in the wrong position.
    Have someone of you a suggestion?
    That will be great.

    Thanks yutianyi

  15. Manas said

    I am also having the same problem as mentioned by yutianyi. Any help would be appreciated.

    Thanks,
    Manas

  16. lili said

    Hi Rakesh Laveti,

    I really need to get this one working. I am new to sharepoint. Would you provide all the source code for the web parts?

    thank you

  17. lili said

    my is working. I had multipul auto complete ajax on a web parts. it is working well.

  18. raj said

    hi,

    with out web service can we implement autocomplete extender in sharepoint. can we get sharepoint list’s field data in Auto complete Extender.
    Reply me asap.

  19. Ajan said

    Hi Lili,

    I am also struggling to to make WebUserControl for AutoCompleteExtender in WSS 3.0.

    Can you please tell me how it worked for you? Where you kept where you kept webservice for AutoComplete?

    Any help will be greatly appreciated.

    Thanks,
    Ajay

  20. swatee katiyar said

    Hi I am trying to add dynamically 3text boxes every time a ADD button is clicked.
    for the first of the 3 text boxes I am trying to add a AutoCompleteExtender every time a Add Button is clicked.

    Here my code: it shows a error everytime that “the targetID cannot be set null”

    C# file code

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Text;

    public partial class medicine_test : System.Web.UI.Page
    {
    int cnt = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
    int.TryParse(txtCount.Text, out cnt);
    AddCtrl(cnt);
    }

    protected void btnAddTextBox_Click(object sender, EventArgs e)
    {

    cnt += 3;
    txtCount.Text = (cnt).ToString();
    //
    AddCtrl(3);

    // label1.Text = “”;
    }

    private void AddCtrl(int cnt)
    {

    if (cnt > 0)
    {
    // StringBuilder htmlstr = new StringBuilder();
    for (int i = 1; i <= cnt; i++)
    {
    TextBox txt = new TextBox();

    txt.ID = "txt" + pnlTextBox.Controls.Count.ToString();
    txt.Text = txt.ID;
    if (i == 1)
    {
    var b = txt.ID;
    label2.Text = "text number" + b.ToString();
    txt.Text = "Tbox" + b.ToString();

    autoCompleteExntenderNew.ID = "AutoCATbox" + b.ToString();
    autoCompleteExntenderNew.TargetControlID = "txt" + b.ToString();
    autoCompleteExntenderNew.BehaviorID = autoCompleteExntenderNew.ID.ToString();
    autoCompleteExntenderNew.Enabled = true;
    autoCompleteExntenderNew.ServicePath = "";
    autoCompleteExntenderNew.ServiceMethod = "SearchMedicineAuto";
    autoCompleteExntenderNew.MinimumPrefixLength = 1;
    pnlTextBox.Controls.Add(autoCompleteExntenderNew);

    }
    pnlTextBox.Controls.Add(txt);

    //SearchMedicine();

    // label1.Text = "”;
    }
    // viewid.Text += htmlstr.ToString();

    }
    }

    public static List SearchMedicineAuto(string prefixText, int count)
    {

    SqlConnection conn;
    SqlCommand cmd;
    conn = new SqlConnection(@”Data Source=SWATEEKATIYAR\SQLEXPRESS;Initial Catalog=chest;User ID=adminchest;Password=password_15;”);

    string cmdstring = “select * from medicine where name like @medicinename + ‘%'”;
    cmd = new SqlCommand(cmdstring, conn);

    cmd.Parameters.AddWithValue(“@medicinename”, prefixText);
    conn.Open();
    List medicineitem = new List();
    using (SqlDataReader sdr = cmd.ExecuteReader())
    {
    while (sdr.Read())
    {

    medicineitem.Add(sdr[“name”].ToString());
    // displaydata();
    }
    }

    conn.Close();
    return medicineitem;
    }

    [System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod]

    public static List SearchMedicine(string prefixText, int count)
    {
    SqlConnection conn;
    SqlCommand cmd;
    conn = new SqlConnection(@”Data Source=SWATEEKATIYAR\SQLEXPRESS;Initial Catalog=chest;User ID=adminchest;Password=password_15;”);

    string cmdstring = “select * from medicine where name like @medicinename + ‘%'”;
    cmd = new SqlCommand(cmdstring, conn);

    cmd.Parameters.AddWithValue(“@medicinename”, prefixText);
    conn.Open();
    List medicineitem = new List();
    using (SqlDataReader sdr = cmd.ExecuteReader())
    {
    while (sdr.Read())
    {

    medicineitem.Add(sdr[“name”].ToString());
    // displaydata();
    }
    }

    conn.Close();
    return medicineitem;
    }

    [System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod]

    protected void LoadMedicine(object sender, EventArgs e)
    {
    SqlConnection conn;
    SqlCommand cmd;
    conn = new SqlConnection(@”Data Source=SWATEEKATIYAR\SQLEXPRESS;Initial Catalog=chest;User ID=adminchest;Password=password_15;”);

    string cmdstring = “select * from medicine where name like ‘” + tboxaddmedicine.Text + “‘”;
    cmd = new SqlCommand(cmdstring, conn);
    SqlDataReader reader;
    try
    {
    conn.Open();
    reader = cmd.ExecuteReader();
    reader.Read();
    medDose.Text = reader[“dose”].ToString();
    medInstructions.Text = reader[“instructions”].ToString();
    reader.Close();
    }
    catch(Exception err)
    {
    label2.Text = err.Message;
    }
    finally
    {
    conn.Close();
    }
    }

    }

    Here is my HTML CODE

    AJAX tool kit script manager

    Medicine:

    Dose:
    Instructions:
    Quantity:
    Add 3 textboxes at a time

  21. am getting file not fount error can u tell me why?

  22. Aditya Reddy said

    Where can i find Microsoft.Web.Extension.dll?

  23. chanel 値段

Leave a reply to Ajan Cancel reply