Showing posts with label autocomplete. Show all posts
Showing posts with label autocomplete. Show all posts

Monday, March 26, 2012

AJAX AutoPostBack not working...:(

Hi!

I've read a few posts about not working autocomplete, but I haven't found anything that would help me get my autocomplete in action. Here's my code and I hope someone can tell me what am I doing wrong...:

WebService:

<%

@dotnet.itags.org.WebServiceLanguage="C#"Class="WebService" %>

using

System;

using

System.Web;

using

System.Web.Services;

using

System.Web.Services.Protocols;

using

System.Web.Script.Services;

using

System.Web.Configuration;

using

System.Data.SqlClient;

using

System.Collections;

[

WebService(Namespace ="http://tempuri.org/")]

[

WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

public

classWebService : System.Web.Services.WebService {

[

WebMethod]

[

ScriptMethod]publicstring[] GetCompletionList(string prefixText,int count)

{

ArrayList list =newArrayList();

string connStringCompletionList =WebConfigurationManager.ConnectionStrings["NeolabConnectionString"].ConnectionString;SqlConnection connCompletionList =newSqlConnection(connStringCompletionList);

connCompletionList.Open();

SqlCommand cmdCompletionList =newSqlCommand("SELECT Seminar FROM Seminar ORDER BY Seminar;", connCompletionList);SqlDataReader rCompletionList = cmdCompletionList.ExecuteReader();while (rCompletionList.Read())

{

list.Add(rCompletionList.GetString(0));

}

string[] completionList = (string[])list.ToArray(typeof(string));return completionList;

}

}

(WebService looks to work just fine, it creates an XML filled with all items)

The page (actually it's a control)

<%

@dotnet.itags.org.ControlLanguage="C#"AutoEventWireup="true"CodeFile="SeminarjiFilter.ascx.cs"Inherits="UC_I_SeminarjiFilter" %>

<%

@dotnet.itags.org.RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="cc1" %>

<

asp:ScriptManagerID="ScriptManager1"runat="server"/>

<

h1>Filter</h1>

<

divclass="crta"></div><tablecellpadding="0"cellspacing="0"border="0"width="100%"runat="server">

<tr><td>

Seminar:

</td><td><cc1:AutoCompleteExtenderID="AutoCompleteExtender1"runat="server"TargetControlID="TextBox1"ServiceMethod="GetCompletionList"ServicePath="/WebService.asmx"MinimumPrefixLength="2"CompletionInterval="1000"EnableCaching="true"CompletionSetCount="12"></cc1:AutoCompleteExtender><asp:TextBoxID="TextBox1"runat="server"CssClass="input"AutoCompleteType="Disabled"/></td></tr>

Can anyone help me? I just can't find what am I doing wrong.

Thx!

p.s.: I'm using Visual Studio Web Developer 2005

Your webservice needs a ScriptService attribute. You do not need the ScriptMethod attribute on the method since this is not a page method.

Hi kirtid!

thx for your help, but it's still not working :(

I've added a ScripService attribute like you have suggested, so my WebService.asmx looks like that now:

<%

@.WebServiceLanguage="C#"Class="WebService" %>

using

System;

using

System.Web;

using

System.Web.Services;

using

System.Web.Services.Protocols;

using

System.Web.Script.Services;

using

System.Web.Configuration;

using

System.Data.SqlClient;

using

System.Collections;

[

ScriptService]

[

WebService(Namespace ="http://tempuri.org/")]

[

WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

public

classWebService : System.Web.Services.WebService {

[

WebMethod]publicstring[] GetCompletionList(string prefixText,int count)

{

ArrayList list =newArrayList();

string connStringCompletionList =WebConfigurationManager.ConnectionStrings["NeolabConnectionString"].ConnectionString;SqlConnection connCompletionList =newSqlConnection(connStringCompletionList);

connCompletionList.Open();

SqlCommand cmdCompletionList =newSqlCommand("SELECT Seminar FROM Seminar ORDER BY Seminar;", connCompletionList);SqlDataReader rCompletionList = cmdCompletionList.ExecuteReader();while (rCompletionList.Read())

{

list.Add(rCompletionList.GetString(0));

}

string[] completionList = (string[])list.ToArray(typeof(string));return completionList;

}

}

I do get a JavaScript error in Firefox, which says:

Napaka: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame ::http://localhost:1952/CISEF/ScriptResource.axd?d=jhPPdebJMXZyNg9DlOLOhTS0Nid4TBhKPJdnm84vbDCB2-uUy_FSlPcxjsG2hmQvG2-MIlmaqMJ-KsoNz2f43LUv6JMplLSpW_hbE2koLH81&t=633108756900118528 :: Sys$Net$XMLHttpExecutor$get_statusCode :: line 4166" data: no]

Here's where it happens (file ScriptResource.axd):

function Sys$Net$XMLHttpExecutor$get_statusCode() { /// <value type="Number"></value> if (arguments.length !== 0) throw Error.parameterCount(); if (!this._responseAvailable) { throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusCode')); } if (!this._xmlHttpRequest) { throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_statusCode')); } return this._xmlHttpRequest.status; }
 
Any idea maybe?!?

Is the path to your webservice set in the ServicePath property correct? -> "/WebService.asmx".


Hi kirtid!

Sorry for late reply, I was on vacation :) Thanks for your help! It was a problem in a path like you assumed!

Later

Ajax AutoCompleteExtender causing validators to fire

Hi,

I'm having a problem with validators firing whenever I select an item in a field extended with autocomplete (I guess pressing the enter key is trying to submit the form?). How can I get around this?

Thanks

The autocomplete extender does not stop the enter key event from propagating to the form which causes the validators to kick in. I think we would like to stop that and let the event propagate if an item has been selected. Could you please open a bug on this? Thanks.

AJAX Autocomplete with On mouse over

Hi AJAX xperts,

I have AJAX autocomplete Textbox, which is a user control. i am getting employee details into this text box. upon typing 3 chars it will fetch 20 records which matchs with the prefix text.

I modified _highligted function(item) in Autocomplete.js in order to store emp fullname in window.status .

upon mouse over on this list i need populate employee details like dept, empid, empmanager, empcost center

here is my autocomplese.asmx C# code :

public string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}

string peopledata = ConnectionStrings.GetConnectionString("Peopledata");
using (SqlConnection ConnStr = new SqlConnection(peopledata))
{
ConnStr.Open();
SqlCommand sqlcmd = new SqlCommand("GetPeopleDetails", ConnStr);
sqlcmd.Parameters.Add("@dotnet.itags.org.prefixText", SqlDbType.VarChar, 50).Value = prefixText + "%";
sqlcmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
DataTable dt = new DataTable();
da.Fill(dt);
DataSet ds = new DataSet();
da.Fill(ds);

string[] items = new string[dt.Rows.Count];
int i = 0;
List<String> PeopleData = new List<string>();
foreach (DataRow dr in dt.Rows)
{

items.SetValue(dr["EmpFullName_MngrName"].ToString(), i);

PeopleData.Add(dr["NBKid"].ToString());
PeopleData.Add(dr["PersonNo"].ToString());
PeopleData.Add(dr["CostCenter"].ToString());
PeopleData.Add(dr["Hierarchy"].ToString());

i++;
}
//return PeopleData.ToArray();
return items;
}//end of sqlconnection

} //end of GetCompletionList

here is my java script code:

var obj;
function GetDataViaAJAX()
{
try
{
obj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e1)
{
obj = null;
}
}
if(obj!=null)
{
obj.onreadystatechange = ProcessResponse;
obj.open("POST", "http://localhost/Autocomplete.asmx/GetEmployeeDetails");
obj.setRequestHeader("Host","localhost");
obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
obj.setRequestHeader("Content-Length","12");
obj.send("Name=" + document.getElementById("lblNamevalue").value);
}
return false;
}

function ProcessResponse()
{
if(obj.readyState == 4)
{
if(obj.status == 200)
{
var dsRoot=obj.responseXML.documentElement;
var ddlOrders = document.getElementById("ListBox1");
for (var count = ddlOrders.options.length-1; count >-1; count--)
{
ddlOrders.options[count] = null;
}
var orders = dsRoot.getElementsByTagName('orderid');
var text;
var listItem;
for (var count = 0; count < orders.length; count++)
{
text = (orders[count].textContent || orders[count].innerText || orders[count].text);
listItem = new Option(text, text, false, false);
ddlOrders.options[ddlOrders.length] = listItem;
}
}
else
{
alert("Error retrieving data!" + obj.status);
}
}
}
function SetValue()
{
var selectedvalue=document.getElementById("ListBox1").value;
document.getElementById("Hidden1").value=selectedvalue;
return true;
}

Can anyone help me on this plzzzz......Is it possible to work this functionality with Autocomplete

Hi,

I think you've almost implemented it. And you just need to call this method just after the _highlightItem method in _onListMouseOver.


Hi wen,

I dnt know why IE is throwing me an error in status bar. saying Syntax error.

I have hardcoded person number in autocomplete.js in order to get results, but when it hit GetDataViaAjax(personNo) functoin, it has to pop up alert which i added at the entry point. for my surprise its poping up insted throwing me error in IE status bar as Syntax error..

I am passing person number to FetchEmployeeDetails.aspx in order to fetech details. then i am returning as XML string. once i get XML string i am manipulating in JavaScirpt as follows. plz help me am i missing any thing.

Well beside if i add my function after _onListMouseOver, how do i get ite,.node.value in autocomplete.js ?

Appreciate your help on this

<script language="javascript"
///<summary>
/// This function manually added by krishna, in order to get EMP details.
///</summary
var obj;
function GetDataViaAjax(personNo)
{
alert(personNo);

try
{
obj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
alert(e);
return;

try
{
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e1)
{

obj = null;
}
}
if(obj!=null)
{
obj.onreadystatechange = ProcessResponse;
obj.open("GET", "http://localhost:3024/0rbit/PeopleSelector_UCR/FetchEmployeeDetails.aspx?personNo=" + myPersonNo, true);
obj.send(null);
}
return false;
}
}

//this is ur call back function
function ProcessResponse()
{

if(obj.readyState == 4)
{
if(obj.status == 200)
{
// this is return part form the ajax call page.
// you qry the database and get the person details in xml format.

var dsRoot=obj.responseXML.documentElement;
alert(obj.responseXML.documentElement);
return;

//get the data from the xml
var oName = dsRoot.getElementsByTagName('lblNameValue');
var oStandardID = dsRoot.getElementsByTagName('lblStandardIDvalue');
var oPersonNo = dsRoot.getElementsByTagName('lblpersonNovalue');
var oHeiarchy = dsRoot.getElementsByTagName('lblHeirarchyValue');
var oCostCenter = dsRoot.getElementsByTagName('lblCostCenterValue');
var oManager = dsRoot.getElementsByTagName('lblManagerValue');


var sName = (oName.textContent || oName..innerText || oName.text);
var sStandardID = (oStandardID.textContent || oStandardID..innerText || oStandardID.text);
var sPersonNo = (oPersonNo.textContent || oPersonNo..innerText || oPersonNo.text);
var sHeiarchy = (oHeiarchy.textContent || oHeiarchy..innerText || oHeiarchy.text);
var sCostCenter = (oCostCenter.textContent || oCostCenter..innerText || oCostCenter.text);
var sManager = (oManager.textContent || oManager..innerText || oManager.text);

var lblName = document.getElementById("GetPeopleList1_lblNameValue");
var lblStandardID = document.getElementById("GetPeopleList1_lblStandardIDvalue").innerHTML;
var lblPersonNo = document.getElementById("GetPeopleList1_lblpersonNovalue").innerHTML;
var lblHeiarchy = document.getElementById("GetPeopleList1_lblHeirarchyValue").innerHTML;
var lblCostCenter = document.getElementById("GetPeopleList1_lblCostCenterValue").innerHTML;
var lblManager = document.getElementById("GetPeopleList1_lblManagerValue").innerHTML;

if(lblName) {lblName.innerHTML = sName; }
if(lblStandardID){lblStandardID.innerHTML = sStandardID;}
if(lblPersonNo){lblPersonNo.innerHTML = sPersonNo;}
if(lblHeiarchy){lblHeiarchy.innerHTML = sHeiarchy;}
if(lblCostCenter){lblCostCenter.innerHTML = sCostCenter;}
if(lblManager){lblManager.innerHTML = sManager;}


}
else
{
alert("Error retrieving data!" );
}
}
}

</script>


If you get an error on the line "alert(personNo)", it's very likely that personNo is null. You may confirm this by double click the error icon in that status bar. If this is the cause, you need to check the code that calls the GetDataViaAjax method to make sure a valid personNo is passed in.

I noticed that in your code, a GET request is send to a .aspx page, so please make sure the response of this request is a XML document. This can be verified by pasting the url "http://localhost:3024/0rbit/PeopleSelector_UCR/FetchEmployeeDetails.aspx?personNo=aPersonNo" in to IE. And you can useXMLDom on client side to process the response.


Hi raymond,

thanks again for your post,

you are right i am redirecting to aspx in order to fetch results,

here is the code in aspx page, in the final am returning XML

DataSet ds = new DataSet();
string peopledata = ConnectionStrings.GetConnectionString("Peopledata");
using (SqlConnection ConnStr = new SqlConnection(peopledata))
{
ConnStr.Open();
SqlCommand sqlcmd = new SqlCommand("GetEmployeeDetails", ConnStr);
sqlcmd.Parameters.Add("@.PersonNO", SqlDbType.VarChar, 50).Value = Request.QueryString["personNo"];
//sqlcmd.Parameters.Add("@.PersonNO", SqlDbType.VarChar, 50).Value = "10525119";
sqlcmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
da.Fill(ds, "Employees");

Response.Clear();
Response.ContentType = "text/xml";
Response.Write(ds.GetXml());
Response.End();
ConnStr.Close();

As of now am sending personNo (a hardcoded value) from Autocomplete.js as GetDataViaAjax("10525119")

Once page returns from FetchemployeeDetails.aspx , i could not see anything.

Well you are taking about XMLDOM, when i am returning XML from ASPX page do i need to parse it again at client side ?


krishnanellutla:

Well you are taking about XMLDOM, when i am returning XML from ASPX page do i need to parse it again at client side ?

Yes but not necessary. XMLDom gives you a convenient way to process it. You could also process it via your own method just like processing some text.


HI raymond,

I could able to display details for the hardcoded value in Autocomplete.js.

I am passing a hardcoded value from Autocomplete.js as GetDataViaAjax("123456789" ); based on this value i am querying database to fetech details and returning XML dcoument on the client side, with ProcessResponse function iam storing details for respective label controls (i took Labels and a panel, for displaying details) .

Now as my code in Autocomplete.asmx returns Employee Fullname, i cannot fetech details based on this fullname. In order to fetch details i have to pass person number to GetDataviaAjax function some thing like GetDataViaAjax(item.firstChild.nodeKeyValue ).

According to thisArticle , if we able to send a key value along with empfullname. my task will be get too easy for dispalying details. I am not sure how it is going to work, but i am gonna work on it.. lets see how it goes

appreciate your prompt responses on this..Thanks bdy !!!


HI Raymond,

Well one more, As of now i am fetching from FetchEmployeeDetails.aspx page, instead of this i would like to use web service (Autocomplete.asmx ) where i would like to add my method in web service. this autocomplete functionality is in User control page.

once again, am pasting whole code for your reference:

JavaScript in GetPeopleDetails.ascx page:

<script language="javascript"
///<summary>
/// This function manually added by krishna, in order to get EMP details.
///</summary
var obj;
function GetDataViaAjax(personNo)
{
var oURLAddress;
var sURLAddress

oURLAddress = document.getElementById("GetPeopleList1_UrlAddress");
if (oURLAddress)
{
sURLAddress = oURLAddress.value;
alert(sURLAddress);
}

try
{

if (window.XMLHttpRequest)
{
// If IE7, Mozilla, Safari, and so on: Use native object.
obj = new XMLHttpRequest();
if(obj!=null)
{
obj.onreadystatechange = ProcessResponse;
obj.open('GET', sURLAddress + 'FetchEmployeeDetails.aspx?personNo=' + personNo, true);
alert("I am Inside XMLHttpRequest");
obj.send(null);
}
}
else if (window.ActiveXObject)
{
// ...otherwise, use the ActiveX control for IE5.x and IE6.
obj = new ActiveXObject('MSXML2.XMLHTTP.3.0');
if(obj!=null)
{
obj.onreadystatechange = ProcessResponse;
obj.open('GET', sURLAddress + 'FetchEmployeeDetails.aspx?personNo=' + personNo, true);
alert("I am Inside ActiveXObject");
obj.send();
}
}

}
catch(e)
{
try
{
obj = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e1)
{

obj = null;
}
}
return false;
}

function ProcessResponse()
{

if(obj.readyState == 4)
{
if(obj.status == 200)
{
// this is return part form the ajax call page.
// you qry the database and get the person details in xml format.
try
{
var dsRoot=obj.responseXML.documentElement;
alert("XML Processed !!!") ;

//get the data from the xml
var oName = dsRoot.getElementsByTagName('EmpFullName')[0].childNodes[0].nodeValue;
var oStandardID = dsRoot.getElementsByTagName('NBKid')[0].childNodes[0].nodeValue;
var oPersonNo = dsRoot.getElementsByTagName('PersonNo')[0].childNodes[0].nodeValue;
var oHeiarchy = dsRoot.getElementsByTagName('Hierarchy')[0].childNodes[0].nodeValue;
var oCostCenter = dsRoot.getElementsByTagName('CostCenter')[0].childNodes[0].nodeValue;
var oManager = dsRoot.getElementsByTagName('MngrFullName')[0].childNodes[0].nodeValue;


var sName = (oName.textContent || oName.innerText || oName.text || oName);
var sStandardID = (oStandardID.textContent || oStandardID.innerText || oStandardID.text || oStandardID);
var sPersonNo = (oPersonNo.textContent || oPersonNo.innerText || oPersonNo.text || oPersonNo);
var sHeiarchy = (oHeiarchy.textContent || oHeiarchy.innerText || oHeiarchy.text || oHeiarchy);
var sCostCenter = (oCostCenter.textContent || oCostCenter.innerText || oCostCenter.text || oCostCenter);
var sManager = (oManager.textContent || oManager.innerText || oManager.text || oManager);

var lblName = document.getElementById("GetPeopleList1_lblNameValue");
var lblStandardID = document.getElementById("GetPeopleList1_lblStandardIDvalue");
var lblPersonNo = document.getElementById("GetPeopleList1_lblpersonNovalue");
var lblHeiarchy = document.getElementById("GetPeopleList1_lblHeirarchyValue");
var lblCostCenter = document.getElementById("GetPeopleList1_lblCostCenterValue");
var lblManager = document.getElementById("GetPeopleList1_lblManagerValue");

if(lblName) {lblName.innerHTML = sName; }
if(lblStandardID){lblStandardID.innerHTML = sStandardID;}
if(lblPersonNo){lblPersonNo.innerHTML = sPersonNo;}
if(lblHeiarchy){lblHeiarchy.innerHTML = sHeiarchy;}
if(lblCostCenter){lblCostCenter.innerHTML = sCostCenter;}
if(lblManager){lblManager.innerHTML = sManager;}

}

catch(e2)
{
alert(e2);
}

}
else
{
alert(obj.responseXML.documentElement);
alert("Status = " + obj.status);
alert("Error retrieving data!" );
}
}
}

</script>

-------------------------------

Autocomplete.asmx code which get results for FullNames :


string peopledata = ConnectionStrings.GetConnectionString("Peopledata");
using (SqlConnection ConnStr = new SqlConnection(peopledata))
{
ConnStr.Open();
SqlCommand sqlcmd = new SqlCommand("GetPeopleDetails", ConnStr);
sqlcmd.Parameters.Add("@.prefixText", SqlDbType.VarChar, 50).Value = prefixText + "%";
sqlcmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
DataTable dt = new DataTable();
da.Fill(dt);
DataSet ds = new DataSet();
da.Fill(ds);
string[] items = new string[dt.Rows.Count];
int i = 0;

foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["EmpFullName_MngrName"].ToString(), i);
i++;
}

//return PeopleData.ToArray();
return items;

-------------------------------

Code in FetchemployeeDetails.aspx

string personNo = Request.QueryString["personNo"];

DataSet ds = new DataSet();
string peopledata = ConnectionStrings.GetConnectionString("Peopledata");
using (SqlConnection ConnStr = new SqlConnection(peopledata))
{
ConnStr.Open();
SqlCommand sqlcmd = new SqlCommand("GetEmployeeDetails", ConnStr);
sqlcmd.Parameters.Add("@.PersonNO", SqlDbType.VarChar, 50).Value = personNo;
//sqlcmd.Parameters.Add("@.PersonNO", SqlDbType.VarChar, 50).Value = "10525119";
sqlcmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
da.Fill(ds, "Employees");

Response.Clear();
Response.ContentType = "text/xml";
Response.Write(ds.GetXml());
Response.End();
ConnStr.Close();

}

-------------------------------

Well in the java script i am calling this FetchemployeeDetails in order to get Employee Details using XMLhttprequest.

intead of going to this aspx page, i would like to put this method in webservice method, and call this method and process accordingly..

So far i never done calling a web service method from java script , can you please help me in modfying this part.

appreciate your help on this..

Thanks in advance


Hi experts,

I am trying to do this whole functionality to a web control library, i added a new instance for AutocompleteExtender in my class. but i could able to find TargetControlID property for this. Can any one help me on this

Ajax AutoComplete with database, not working

Hello,

I am interested in implementing a search box which gives suggestions as you type. So, I downloaded the AjaxControlToolKit source code, I compiled the solution in VS 2005, and it is OK.

Then I modified the [WebMethod] public string[] GetCompletionList(string prefixText, int count) in an attempt to get the string array from a User table in my database.

I don't quite understand this WebMethod. for example,what is prefixText? My modified code is as follows.

1 [WebMethod]2public string[] GetCompletionList(string prefixText,int count)3 {4if (count == 0)5 {6 count = 10;7 }89if (prefixText.Equals("xyz"))10 {11return new string[0];12 }1314string connectionString ="localhost;Initial Catalog=myDatabase; User Id=myUserID; Password=topSecrect";15 SqlConnection sqlConnection =new SqlConnection(connectionString);16 sqlConnection.Open();17 SqlCommand sqlCommand =new SqlCommand("SELECT LASTNAME + ', ' + FIRSTNAME FROM USER AS FULLNAME ORDER BY LASTNAME", sqlConnection);18 SqlDataReader sdr = sqlCommand.ExecuteReader();1920 ArrayList fullNames =new ArrayList(count);2122while (sdr.Read())23 {24if (!sdr.IsDBNull(0))25 {26char c1 = (char)sdr.GetString(0)[0];27char c2 = (char)sdr.GetString(0)[1];28char c3 = (char)sdr.GetString(0)[2];29 fullNames.Add(prefixText + c1 + c2 + c3);30 }3132 }33return (string[])fullNames.ToArray(typeof(string));34 }

Please note that I do not quite understand the part in the for loop as in the original source code shown in blue below. So I am only mimicking the code.

// ArrayList items = new ArrayList(count);
// Random random = new Random();
// for (int i = 0; i < count; i++)
// {
// char c1 = (char)random.Next(65, 90);
// char c2 = (char)random.Next(97, 122);
// char c3 = (char)random.Next(97, 122);

// items.Add(prefixText + c1 + c2 + c3);
// }

Also please note, that the compilation of the solution with the modified code passed, and I can check out http://localhost:7870/ToolkitTests/AutoComplete.aspx just fine, but when I type in the first textbox of this AutoComplete.aspx page, no suggestions show up. The second textbox still works as usual.

The Sql query and connection string are both fine. I ran it in some other applications, they work without a problem.

Any hint is highly appreciated. Thanks.

The prefixText field are the characters that have been typed and are being queried, the count is the max number of records to return then updated with the number of records returned.

The Random... etc code, was just a way for the demo application to generate random data without attaching a database.


jguadagno:

The prefixText field are the characters that have been typed and are being queried, the count is the max number of records to return then updated with the number of records returned.

The Random... etc code, was just a way for the demo application to generate random data without attaching a database.

OK, thanks. My guess about the prefText argument was right. But, what's wrong with my modified code, which attempts to get the suggestions from the database?


Is there a way to get the suggestion list from a database? No one knows?


You have the code in the GetCompletionList. Is it not working. Remember the prefixText are the letters that the text box control has so far. So if the is a Country drop down list as user type U, the prefixText should get a U and you have to return a list of your options that start with U.


OK, I found a sample code at

http://forums.asp.net/p/1126189/1772074.aspx#1772074

By J. Shen, In order to test the dynamic SQL, I created a regular web application (NOT web service!) I just copied the part of the aforementioned code which gets the suggestions from the DB and modified like so:

public string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}

if (prefixText.Equals("xyz"))
{
return new string[0];
}

string connectionString = "Data Source=localhost;Initial Catalog=mydatabase; User Id=myUserID; Password=TopSecret";
SqlConnection sqlConnection = new SqlConnection(connectionString);

SqlCommand sqlCommand = new SqlCommand
("SELECT TOP @.nrows LASTNAME " +
"FROM v_USER " +
"WHERE LASTNAME LIKE @.term " +
"ORDER BY LASTNAME", sqlConnection);
sqlCommand.Parameters.AddWithValue("@.nrows", count);
sqlCommand.Parameters.AddWithValue("@.term", prefixText + "%");

List<string> suggestions = new List<string>();
sqlConnection.Open();

SqlDataReader sdr = sqlCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

while (sdr.Read())
{
suggestions.Add(sdr[0].ToString());
}

sqlConnection.Close();
sdr.Close();

return suggestions.ToArray();

}

As you see, except the SQL, it's the same as that of J. Shen's. I call this method in Page_Load like so:

protected void Page_Load(object sender, EventArgs e)
{

string[] s = GetCompletionList("Joh", 10);
Response.Write(s.Length);
}

When I run the Web application. I always get this error:

Exception Details:System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '@.nrows'.

I am using SQL Server 2000, and obviously, the SQL query syntax isn't accepted by Sql Server 2000. I cannot figure out what's wrong with it. I am new to dynamic sql.

Any hint? Thanks.


The problem is with TOP @.nrows ... You can not have a variable for that. You can build the string prior to

string sql ="SELECT TOP " + count.ToString() +"LASTNAME FROM v_USER ";string sql +=" WHERE LASTNAME LIKE @.term ORDER BY LASTNAME ";SqlCommand sqlCommand =new SqlCommand(sql, sqlConnection);


Thank you very much, Joseph. That was the problem. It's working now. The sample code given by J. Shen completely misled me. I did not cast any doubt on his code because I took it for granted that it was a working sample.


I am glad it worked. Please mark it as "Answered" so that others will know the solution.


Hi All,

I have been trying to replicate this post in VB.net and I "think" I am almost there. I am stuck on a couple of small pieces and I'm begging for help. I have been trying to get the AJAX autocomplete to work off of a SQL database for many hours before I ran into this post which seems promising. I feel I'm at my ends.

I'm having trouble with the following lines, I'm tried to figure out what the code was trying to do but this is what I could come up with and its not working:
----------------------------------
Dim suggestionsAs ListItemCollection =New ListItemCollection(OfString)

While (reader.Read())
suggestions.Add(reader[0].ToString())
EndWhile

Return suggestions.ToArray
----------------------------------

Thanks in advance, I truely appreciate it.
Tim

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Collections.Generic
Imports System.Data.Sql
Imports System.Data.SqlClient

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<System.Web.Script.Services.ScriptService()> _

PublicClass AutoComplete
Inherits System.Web.Services.WebService

<WebMethod()> _

PublicFunction GetCompletionList(ByVal prefixTextAsString,ByVal countAsInteger)AsString()

If (count = 0)Then
count = 10
EndIf

Dim connAs SqlConnection
Dim commAs SqlCommand
Dim readerAs SqlDataReader
Dim connectionstringAsString = ConfigurationManager.ConnectionStrings("Magic").ConnectionString
Dim sqlAsString ="SELECT TOP " + count.ToString() +"LASTNAME FROM v_USER "

sql +=" WHERE LASTNAME LIKE @.term ORDER BY LASTNAME "

conn =New SqlConnection(connectionstring)
comm =New SqlCommand(sql, conn)
comm.Parameters.AddWithValue("@.nrows", count)
comm.Parameters.AddWithValue("@.term", prefixText +"%")

Dim suggestionsAs ListItemCollection =New ListItemCollection(OfString)

conn.Open()
reader = comm.ExecuteReader(System.Data.CommandBehavior.CloseConnection

While (reader.Read())
suggestions.Add(reader[0].ToString())
EndWhile

conn.Close()
reader.Close()

Return suggestions.ToArray

EndFunction
EndClass


With comments

''' Creates a list array

Dim suggestionsAs ListItemCollection =New ListItemCollection(OfString)

''' Opens the connection

conn.Open()

''' Creates a data reader
reader = comm.ExecuteReader(System.Data.CommandBehavior.CloseConnection

''' Loops through the data reader

While (reader.Read())

''' Adds the first column to the suggestions array

''' note: in VB this should read
suggestions.Add(reader(0).ToString())
EndWhile

''' close the objects

conn.Close()
reader.Close()

''' return the suggestion

Return suggestions.ToArray


Almost there...

I have everything compiling correctly, Visual Studio 05 isn't giving me any error messages but when I type in the textbox nothing happens. It must be linked incorrectly. I know the SQL statement works correctly because I ran it in Query Analyzer, and I know the connection string works because I have other data pulling so I think the function GetCompletionList isn't being passed any parameters for it to return a result.

If someone could explain the mapping so I can go back and verify everything on my end that would be good. Currently I have the autocompleteextender controlID set to my textbox. Other than that, the AJAX website knows to use the AutoComplete.asmx which then points to the App_Code/Autocomplete.vb right? Or does this have to be set manually or something.

Idea's?
Thanks!
Tim


The autocompleteextender needs to be configured like this

<ajaxToolkit:AutoCompleteExtender runat="server" ID="autoComplete1" TargetControlID="myTextBox" ServiceMethod="GetCompletionList" ServicePath="AutoComplete.asmx" MinimumPrefixLength="2" CompletionInterval="1000" EnableCaching="true" CompletionSetCount="20" CompletionListCssClass="autocomplete_completionListElement" CompletionListItemCssClass="autocomplete_listItem" CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem" DelimiterCharacters=";, :"> <Animations> <OnShow> ... </OnShow> <OnHide> ... </OnHide> </Animations></ajaxToolkit:AutoCompleteExtender>
Note, the ServiceMethod and ServicePath properties. They need to be pointed to whereever your AutoComplete is.

ajax autocomplete text

Hi,

I downloaded ajax 1.0 beta 2 and the controls toolkit.

I want to make an autocomplete textbox that while typing letters in it,

a dropdownlist is opened under it and filled by ajax with every new letter typed in the textbox.

When choosing a value in the ddl, it disappears and the selected value inserted into the textbox.

I saw such examples in atlas, but I prefer to use ajax 1.0 , since I relized that this is the recommended product.

Is there any control in the controls toolkit for that ? Did somebody here tried it before ?

Thanks a lot !

AutoCompleteExtender currently lives in the Futures CTP:http://www.microsoft.com/downloads/details.aspx?FamilyId=29B6B62B-A25A-498D-AA14-90B68CF2E392&displaylang=en

Ajax AutoComplete Problem

I have been trying to get the AutoComplete work without success. (many Days)

I have a deveplement Server 2003, XP workstation with VS2005 and IE7, and have check this with a workstation with Win98&IE6

I am using the demo from the Ajax.net video's

I have install the lastest ajax onto the server and the bin directory has: AjaxControlToolkit;AjaxControlToolkit.dll;AjaxControlToolkit.dll.refresh;AJAXExtensionsToolbox.dll;BuildVsi.dll;JavaScriptCommentStripper.dll;System.Web.Extensions.Design.dll;System.Web.Extensions.dll;Tools.dll;Tools.netmodule.

I can get things like the CollapsiblePanelExtender working, The demo on the ajax web site works.

The page displays as expected, but when I type the 3rd character, nothing happens

Filddler gives me an error 500, on the 3rd 'a'

I also had to create a folder named 'GetCompletionList' with a copy of autocomplete.asmx in it to fix an error 404 that fiddler gave me, which may be anther issuse.

I can call the web service and get results from it and '/js' gets me the option to download the JavaScript.

=====Fiddler=====

{"prefixText":"aaa","count":10}

-----------

HTTP/1.1 500 Internal Server Error

Date: Sun, 29 Apr 2007 10:35:28 GMT

Server: Microsoft-IIS/6.0

MicrosoftOfficeWebServer: 5.0_Pub

X-Powered-By: ASP.NET

X-AspNet-Version: 2.0.50727

Cache-Control: private

Content-Type: application/soap+xml; charset=utf-8

Content-Length: 1666

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">System.Web.Services.Protocols.SoapException: Server was unable to process request. --> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.

at System.Xml.XmlTextReaderImpl.Throw(Exception e)

at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)

at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()

at System.Xml.XmlTextReaderImpl.ParseDocumentContent()

at System.Xml.XmlTextReaderImpl.Read()

at System.Xml.XmlTextReader.Read()

at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()

at System.Xml.XmlReader.MoveToContent()

at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()

at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()

at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()

at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)

at System.Web.Services.Protocols.SoapServerProtocol.Initialize()

at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)

-- End of inner exception stack trace --</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>

=====Default.aspx=====

<%

@dotnet.itags.org.PageLanguage="VB"AutoEventWireup="true"CodeFile="Default.aspx.vb"Inherits="_Default" %>

<%

@dotnet.itags.org.RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="cc1" %>

<!

DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<

htmlxmlns="http://www.w3.org/1999/xhtml">

<

headrunat="server"><title>Ajax Test</title>

</

head>

<

body><formid="form1"runat="server"><asp:ScriptManagerID="ScriptManager1"runat="server"><Services><asp:ServiceReferencePath="AutoComplete.asmx"/></Services></asp:ScriptManager><asp:TextBoxID="TextBox1"runat="server"></asp:TextBox><br/><cc1:AutoCompleteExtenderid="AutoCompleteExtender1"runat="server"ServiceMethod="AutoComplete.asmx"ServicePath="GetCompletionList"TargetControlID="TextBox1"></cc1:AutoCompleteExtender></form>

</

body>

</

html>

=====AutoComplete.asmx=====

<%

@dotnet.itags.org.WebServiceLanguage="VB"CodeBehind="~/App_Code/AutoComplete.vb"Class="AutoComplete" %>

=====App_Code/AutoComplete.vb=====

Imports

System.Web

Imports

System.Web.Services

Imports

System.Web.Services.Protocols

Imports

System.Collections.Generic

'from line 10( before ScriptService): <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

<WebService(Namespace:=

"http://tempuri.org/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<System.Web.Script.Services.ScriptService()> _

Public

Class AutoCompleteInherits System.Web.Services.WebService

<WebMethod()> _

PublicFunction GetCompletionList(ByVal prefixTextAsString,ByVal countAsInteger)AsString()Dim c1AsCharDim c2AsCharDim c3AsCharIf (count = 0)Then

count = 10

EndIfDim rndAsNew Random()Dim itemsAsNew List(OfString)For iAsInteger = 1To count

c1 =

CStr(rnd.Next(65, 90))

c2 =

CStr(rnd.Next(97, 122))

c3 =

CStr(rnd.Next(97, 122))

items.Add(prefixText + c1 + c2 + c3)

Next iReturn items.ToArray()EndFunction

End

Class

=====Web.config=====

<?

xmlversion="1.0"?>

<

configuration>

<

configSections>

<

sectionGroupname="system.web.extensions"type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

<

sectionGroupname="scripting"type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

<

sectionname="scriptResourceHandler"type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"requirePermission="false"allowDefinition="MachineToApplication"/>

<

sectionGroupname="webServices"type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

<

sectionname="jsonSerialization"type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"requirePermission="false"allowDefinition="Everywhere"/>

<

sectionname="profileService"type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"requirePermission="false"allowDefinition="MachineToApplication"/>

<

sectionname="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>

</

configSections>

<

system.web>

<!--

MarkRoss: Next line added to fix remote error message-->

<

customErrorsmode="Off"/>

<

webServices>

<

protocols>

<

addname="HttpGet"/>

<

addname="HttpPost"/>

</

protocols>

</

webServices>

<

pages>

<

controls>

<

addtagPrefix="asp"namespace="System.Web.UI"assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

</

controls>

</

pages>

<!--

Set compilation debug="true" to insert debugging

symbols into the compiled page. Because this

affects performance, set this value to true only

during development.

-->

<

compilationdebug="false">

<

assemblies>

<

addassembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<

addassembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>

<

addassembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></assemblies>

</

compilation>

<

httpHandlers>

<

removeverb="*"path="*.asmx"/>

<

addverb="*"path="*.asmx"validate="false"type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<

addverb="*"path="*_AppService.axd"validate="false"type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<

addverb="GET,HEAD"path="ScriptResource.axd"type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"validate="false"/>

</

httpHandlers>

<

httpModules>

<

addname="ScriptModule"type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

</

httpModules>

</

system.web>

<

system.web.extensions>

<

scripting>

<

webServices>

<!--

Uncomment this line to customize maxJsonLength and add a custom converter-->

<!--

<jsonSerialization maxJsonLength="500">

<converters>

<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>

</converters>

</jsonSerialization>

-->

<!--

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>

<

validationvalidateIntegratedModeConfiguration="false"/>

<

modules>

<

addname="ScriptModule"preCondition="integratedMode"type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

</

modules>

<

handlers>

<

removename="WebServiceHandlerFactory-Integrated"/>

<

addname="ScriptHandlerFactory"verb="*"path="*.asmx"preCondition="integratedMode"type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<

addname="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"/>

<

addname="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>

</

configuration>

I have resolved this

in:-

<cc1:AutoCompleteExtenderid="AutoCompleteExtender1"runat="server"ServiceMethod="AutoComplete.asmx"

ServicePath="GetCompletionList"TargetControlID="TextBox1">

</cc1:AutoCompleteExtender>

I had theServiceMethod& ServicePath attributes back to front

Note: Using Fiddler helped, couldn't see this problem initially due to its simplicity

"I also had to create a folder named 'GetCompletionList' with a copy of autocomplete.asmx in it to fix an error 404 that fiddler gave me, which may be anther issuse."

AJAX AutoComplete not completing text?

Hi

The AJAX AutoComplete is not returning any values when users type in text in the TextBox1.

Here is my ASPX code:

<%@dotnet.itags.org.PageLanguage="C#"AutoEventWireup="true"CodeFile="Test.aspx.cs"Inherits="Test" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

</head>

<body>

<formid="form1"runat="server">

<div>

<asp:ScriptManagerID="ScriptManager1"runat="server">

<Services>

<asp:ServiceReferencePath="~/DynamboWebService.asmx"/>

</Services>

</asp:ScriptManager>

<asp:TextBoxID="TextBox1"runat="server"></asp:TextBox>

<ajaxToolkit:AutoCompleteExtenderID="AutoCompleteExtender1"runat="server"TargetControlID="TextBox1"ServicePath="~/DynamboWebService.asmx"ServiceMethod="GetProvincesStates"CompletionSetCount="3"MinimumPrefixLength="2">

</ajaxToolkit:AutoCompleteExtender>

</div>

</form>

</body>

</html>

This is my Web Service Code (DynamboWebService.asmx):

using System;

using System.Web;

using System.Collections;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Web.UI.WebControls;

using System.Configuration;

using System.Security;

using System.Data;

using System.Data.Sql;

using System.Data.SqlClient;

using System.IO;

using System.Net.Mail;

using System.Collections.Generic;

///<summary>

/// Summary description for DynamboWebService

///</summary>

[WebService(Namespace ="http://tempuri.org/")]

[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

publicclassDynamboWebService : System.Web.Services.WebService {

public DynamboWebService () {

//Uncomment the following line if using designed components

//InitializeComponent();

}

[System.Web.Services.WebMethod]

[System.Web.Script.Services.ScriptMethod]

publicstring[] GetProvincesStates(string prefixText,int count)

{

if (count == 0)

{

count = 10;

}

if (prefixText.Equals("xyz"))

{

returnnewstring[0];

}

Random random =newRandom();

List<string> items =newList<string>(count);

//Usually, here is a sqlstate to get some records.

for (int i = 0; i < count; i++)

{

char c1 = (char)random.Next(65, 90);

char c2 = (char)random.Next(97, 122);

char c3 = (char)random.Next(97, 122);

items.Add(prefixText + c1 + c2 + c3);

}

return items.ToArray();

}

}

Does anyone have any suggestions? I am pretty sure the Web Service is functioning and returning values.

Thanks for your help in advance.

Regards
Edward

Hi,

Please change:

[WebService(Namespace ="http://tempuri.org/")]

[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

publicclassDynamboWebService : System.Web.Services.WebService {

public DynamboWebService () {

//Uncomment the following line if using designed components

//InitializeComponent();

}

[System.Web.Services.WebMethod]

[System.Web.Script.Services.ScriptMethod]

publicstring[] GetProvincesStates(string prefixText,int count)

To:

[WebService(Namespace ="http://tempuri.org/")]

[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]

publicclassDynamboWebService : System.Web.Services.WebService {

public DynamboWebService () {

//Uncomment the following line if using designed components

//InitializeComponent();

}

[System.Web.Services.WebMethod]

publicstring[] GetProvincesStates(string prefixText,int count)

,then it should work.

And you don't need:

<Services>

<asp:ServiceReferencePath="~/DynamboWebService.asmx"/>

</Services>

Best Regards,


Hi Thanks for your help - it worked!

Now I encountered another problem all of a sudden:

I'm using:

ASP.NET 2 Wizard Control inside an Update Panel

Don't worry, found the problem: Both AutoComplete Extenders had the sameBehaviorID

Ajax autocomplete method

Hi! Is there an example of doing the ajax autocomplete using sql as the back end. This is the method they have on there:publicstring[] GetCompletionList(string prefixText,int count)

{

if (count == 0)

{

count = 10;

}

Random random =newRandom();

List<string> items =newList<string>(count);

for (int i = 0; i < count; i++)

{

char c1 = (char)random.Next(65, 90);

char c2 = (char)random.Next(97, 122);

char c3 = (char)random.Next(97, 122);

items.Add(prefixText + c1 + c2 + c3);

}

return items.ToArray();

}

Basically I'd like to change this method to be an sql server method. Thanks for any tips

This is a stripped down example that might help get you started:

 [WebMethod]
public string[] GetCustomerList(string prefixText,int count)
{
OleDbConnection conn =new OleDbConnection("ConnectionStringGoesHere");
OleDbCommand cmd =new OleDbCommand();

cmd.Connection = conn;

cmd.CommandText =string.Format("select customer_name from customers where customer_name like '%{0}%'", prefixText);

conn.Open();

OleDbDataReader dr = cmd.ExecuteReader();

List<string> result =new List<string>();

while (dr.Read())
result.Add(dr[0].ToString());

conn.Close();

return result.ToArray();
}

Please note, it isn't really representative of following database best practices. It should point you in the right direction though.

Thank you! Works good!


Just make sure you tidy up the database access if you're going to use this in production. That code is vulnerable to SQL injection, which is fairly bad when it's hooked up to a web service.

Ajax autocomplete - problem with scrollbar

I've implemented autocomplete extender with a textbox,

I'm retreiving thousands of records in the autocomplete search, and depending on the value selected in the autocomplete search results i'm doing some other operation. ( I've associated a textchanged event with the textbox ).

My Problem - Though i'm retreiving thousands of records in the search, but the moment i drag the scrollbar to scroll down to see results, the textbox event is triggered and the scrollbar disappears. i.e i'm not able to scroll through the records.

I'm stuck on this issue for days now. Please suggest me a way so that i can scroll down all the records and able to trigger event based on the record selection.

Many thanks,

DotNetSpidy

MCP, MCTS

HAI I have just joined ajax community

I have read ur question and i just the problem here is that , u are using textchanged event due to when next item get selected textbox event is triggered ,

i will u to try lostfocus event for textbox , in this case when u can scroll all the values and event will be triggered as soon as textbox lost focus . (this is the way i use )

IS this helpful , please remind me


Can you post your code so we can get a full picture of what you are doing?

Tim


HI, thanks for replies,

I found the solution, set the Autopostback = false, use Ajax latest control toolkit, and implemented a OnClientItemSelected event of the Autocomplete extender, then i handled the event.

Thanks for help,

dotNetSpidy