Webmethod from WebService doesn't fire for AJAX AutoCompleteExtender and UpdatePanel - asp.net

Here is code:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true"
AsyncPostBackTimeout="1000" ScriptMode="Release"
EnablePartialRendering="true" >
<Services>
<asp:ServiceReference Path ="~/FolderForService/Service.asmx" />
</Services>
<Scripts>
<asp:ScriptReference Path="~/jscript/common.js" />
</Scripts>
</asp:ScriptManager>
<asp:UpdatePanel ID="upFSK" runat ="server" UpdateMode ="Conditional" >
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server" >
<asp:TextBox ID="TextBox1" runat="server" Visible="True" Width="128px"></asp:TextBox>
<cc1:AutoCompleteExtender ID="ACE"
runat="server"
ServicePath="~/FolderForService/Service.asmx"
ServiceMethod="WebMethod"
MinimumPrefixLength="4"
CompletionSetCount = "10"
TargetControlID="TextBox1">
</cc1:AutoCompleteExtender>
</Panel>
</ContentTemplate>
</UpdatePanel>
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Linq
Imports System.Web.Caching
Imports System.Data
Imports System.Collections.Generic
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
Inherits System.Web.Services.WebService
'Web method which doesn't fire
<WebMethod()> _
Public Shared Function WebMethod(ByVal prefixTekst As String, ByVal count As Integer) As List(Of String)
' Code
End Function
End Class
What I did:
I moved textbox outside Update Panel - 0 points
Changed WebMethod from shared to instance - 0 points
Moved WebService to root - 0 points
Added PostBack=true and Triggers to UpdatePanel with textbox as a trigger - 0 points
Created new WebSite with AutoComplete TextBox and without UpdatePanel - 10 points
What did I miss?

I've only done this in c#, I can give you a c# example if you request it otherwise check out this resource, it should help you get this operational. http://www.aspsnippets.com/Articles/ASP.Net-AJAX-Control-Toolkit-AutoCompleteExtender-without-using-Web-Services.aspx
From the link:
ASP:
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnablePageMethods = "true">
</asp:ScriptManager>
<asp:TextBox ID="txtContactsSearch" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers"
MinimumPrefixLength="2"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="txtContactsSearch"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
</cc1:AutoCompleteExtender>
VB:
<System.Web.Script.Services.ScriptMethod(), _
System.Web.Services.WebMethod()> _
Public Shared Function SearchCustomers(ByVal prefixText As String, ByVal count As Integer) As List(Of String)
Dim conn As SqlConnection = New SqlConnection
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("constr").ConnectionString
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "select ContactName from Customers where" & _
" ContactName like #SearchText + '%'"
cmd.Parameters.AddWithValue("#SearchText", prefixText)
cmd.Connection = conn
conn.Open()
Dim customers As List(Of String) = New List(Of String)
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
customers.Add(sdr("ContactName").ToString)
End While
conn.Close()
Return customers
End Function

Set your page property EnableEventValidation="false".It will work.

Related

ASP TImer, UpdatePanel and UpdatePanelAnimationExtender

When I make use of the Timer event tick to trigger an animated update panel refresh I get the following error:
TypeError: sender._activeElement is undefined
Sys.Extended.UI.Animation.UpdatePanelAnimationBehavior.prototype._partialUpdateBeginRequest()
ScriptResource.axd:75
Function$createDelegate/<()
ScriptResource.axd:47
Sys$EventHandlerList$getHandler/<()
ScriptResource.axd:3484
Sys$WebForms$PageRequestManager$_onFormSubmit()
ScriptResource.axd:1284
Sys$WebForms$PageRequestManager$_doPostBack()
ScriptResource.axd:824
Function$createDelegate/<()
ScriptResource.axd:47
Sys$UI$_Timer$_doPostback()
ScriptResource.axd:60
Sys$UI$_Timer$_raiseTick()
ScriptResource.axd:91
Function$createDelegate/<()
If I use a button click event it works fine animations and all, but I need it timed. If I remove the UpdatePanelAnimationExtender the timer refresh works fine but I don't get the animations.
I am using Ajax Control Toolkit 16.
<%# Page Language="VB" AutoEventWireup="True" CodeFile="Test2.aspx.vb" Inherits="_Default" Debug="True" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="ds2.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<asp:scriptmanager ID="Scriptmanager1" runat="server"></asp:scriptmanager>
<div><div style="float:right; color:gray;"><asp:Label Visible="true" ID="Label1" runat="server" Text="1"></asp:Label></div>
<ajaxToolkit:UpdatePanelAnimationExtender ID="UpdatePanelAnimationExtender1" runat="server" TargetControlID="logoUpdatePanel">
<Animations><OnUpdating><Sequence>
<EnableAction AnimationTarget="effect_color" Enabled="true" />
<EnableAction AnimationTarget="effect_collapse" Enabled="true" />
<EnableAction AnimationTarget="effect_fade" Enabled="true" />
<Parallel Duration="1" Fps="20">
<FadeOut AnimationTarget="PanelInfo" minimumOpacity=".2" />
<color AnimationTarget="PanelInfo" StartValue="#FFEF3F" EndValue="#FFFFFF" Property="style" PropertyKey="backgroundColor" />
</Parallel></Sequence></OnUpdating>
<OnUpdated>
<Sequence>
<EnableAction AnimationTarget="effect_collapse" Enabled="true" />
<EnableAction AnimationTarget="effect_fade" Enabled="true" />
<Parallel Duration="1" Fps="20">
<FadeIn AnimationTarget="logoUpdatePanel" />
<Resize Height="0" />
</Parallel>
</Sequence>
</OnUpdated></Animations>
</ajaxToolkit:UpdatePanelAnimationExtender>
<asp:UpdatePanel ID="logoUpdatePanel" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Image ID="Logo1" runat="server" ImageUrl="~/Images/RBCCCW_1080p_Horizontal.jpg" ImageAlign="Middle" />
<asp:Label Visible="false" runat="server" ID="TableCount" Text="tablecount"></asp:Label>
<asp:Label visible="false" runat="server" ID="rowcount" Text="rowcount"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</div>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" updatemode="Conditional">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="10000" OnTick="bindlist"></asp:Timer>
<asp:DataList ID="RoomEventsList" runat="server" Width="1080px" CellPadding="10" CellSpacing="5" HeaderStyle-BackColor="#0060AA" AlternatingItemStyle-BackColor="#a8cde2" Font-Size="24pt">
<HeaderTemplate>
<div class="colhead1">Start</div><div class="colhead2">Events</div>
</HeaderTemplate>
<ItemTemplate>
<div class="col1"><%#Eval("fstf").ToString.ToLower()%></div><div class="col2"><span style="font-weight:bold"><%#Eval("EV700_ALT_FUNC_DESC")%></span> <br /><span style="float:right;font-size:22pt"> <%#Eval("EV800_SPACE_DESC")%> | <%#Eval("EV812_HIER_LVL2_DESC")%> | <%#Eval("EV811_HIER_LVL1_DESC")%> </span></div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:DataList>
<table width="100%"><tr><td></td><td align="right">
<asp:Label Visible="false" runat="server" ID="pagenumber" Text="start"></asp:Label><asp:Label Visible="false" ID="lblTotalPages" runat="server" Text="1"></asp:Label></td></tr></table>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
and the code behind:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Imports System.Collections.Generic
Imports System.Configuration
Partial Class _Default
Inherits System.Web.UI.Page
Dim pagedDSr As New PagedDataSource()
Dim totalPages As Integer
Dim totalImages As Integer
Public Property CurrentPage() As Integer
Get
Return IIf(ViewState("CurrentPage") Is Nothing, 0, CInt(ViewState("CurrentPage")))
End Get
Set(value As Integer)
ViewState("CurrentPage") = value
End Set
End Property
Public Property imagecount() As Integer
Get
Return IIf(ViewState("imagecount") Is Nothing, 0, CInt(ViewState("imagecount")))
End Get
Set(value As Integer)
ViewState("imagecount") = value
End Set
End Property
Public Property imageSize() As String
Get
Return IIf(ViewState("imageSize") Is Nothing, "", CStr(ViewState("imageSize")))
End Get
Set(value As String)
ViewState("imageSize") = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack() Then
CurrentPage = 0
imagecount = 1
TableCount.Text = "0"
bindlist()
End If
End Sub
Sub changelogo()
Logo1.ImageUrl = "~/Images/" & imagesize & "/" & imagecount & ".jpg"
If imagecount = IO.Directory.GetFiles("C:\inetpub\digsignall\Images\" & imageSize & "\", "*.jpg").Length Then
imagecount = 1
TableCount.Text = imagecount.ToString
Else
imagecount = imagecount + 1
TableCount.Text = imagecount.ToString
End If
End Sub
Sub bindlist()
Dim strConnString As String = ConfigurationManager.ConnectionStrings("ebmsprodCS").ConnectionString
Dim con As New SqlConnection(strConnString)
Using conn As New SqlConnection(strConnString)
Dim varname1 As New System.Text.StringBuilder
varname1.Append("SELECT statement removed for space")
Dim cmd As New SqlCommand(varname1.ToString, conn)
cmd.CommandType = CommandType.Text
conn.Open()
'Dim drEvents As SqlDataReader = cmd.ExecuteReader()
Dim eventsda = New SqlDataAdapter(cmd)
Dim ds = New DataSet
eventsda.Fill(ds, "events")
If ds.Tables(0).Rows.Count <= 0 Then
RoomEventsList.Visible = False
imagesize = "fullscreen"
rowcount.Text = IO.Directory.GetFiles("C:\inetpub\digsignall\Images\" & imageSize & "\", "*.jpg").Length
changelogo()
Else
RoomEventsList.Visible = True
imageSize = "top"
changelogo()
End If
pagedDSr.DataSource = ds.Tables(0).DefaultView
pagedDSr.AllowPaging = True
pagedDSr.PageSize = 10
pagedDSr.CurrentPageIndex = CurrentPage
totalPages = pagedDSr.PageCount
RoomEventsList.DataSource = pagedDSr
RoomEventsList.DataBind()
conn.Close()
Label1.Text = Request.QueryString("room")
End Using
If pagedDSr.IsLastPage Then
CurrentPage = 0
Else
CurrentPage = CurrentPage + 1
End If
pagenumber.Text = CurrentPage.ToString
End Sub
Protected Sub bindlist_tick()
pagedDSr.CurrentPageIndex = CurrentPage
RoomEventsList.DataSource = pagedDSr
RoomEventsList.DataBind()
If pagedDSr.IsLastPage Then
CurrentPage = 0
Else
CurrentPage = CurrentPage + 1
End If
pagenumber.Text = CurrentPage.ToString
End Sub
End Class

ASP.net auto complete works in local, but not working in live server

We have an ASP website that has the auto complete function for textbox. When we test on local, the function able to work. After we host the website on live server, we found that the auto complete function is not working anymore. We need to make that function works on the live server as well. We develop the website using Visual Studio tool. However, our live server did not have Visual Studio. We hosted the website using IIS 8 on the server. We need help on this issue.
Below are the details of codes.
We created a class called AutoComplete.vb in the App_Code folder. Below are the coding.
AutoComplete.vb
Imports System
Imports System.Collections
Imports System.Linq
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml.Linq
Imports System.Collections.Generic
Imports System.Data
Imports System.Data.SqlClient
' To allow this Web Service to be called from script, using ASP.NET AJAX,
' uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class AutoComplete
Inherits System.Web.Services.WebService
Dim cn As New SqlClient.SqlConnection()
Dim ds As New DataSet
Dim dt As New DataTable
<WebMethod()> _
Public Function GetCompletionList(ByVal prefixText As String, _
ByVal count As Integer) As String()
'ADO.Net
Dim strCn As String = _
"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\MSDRepairWebDB\App_Data\Errorcode.mdf;Integrated Security=True;User Instance=True"
cn.ConnectionString = strCn
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cn
cmd.CommandType = CommandType.Text
'Compare String From Textbox(prefixText)
'AND String From Column in DataBase(CompanyName)
'If String from DataBase is equal to String from TextBox(prefixText)
'then add it to return ItemList
'-----I defined a parameter instead of passing value
'directly to prevent SQL injection--------'
cmd.CommandText = "select * from Errorcode Where Test like #myParameter"
cmd.Parameters.AddWithValue("#myParameter", prefixText + "%")
Try
cn.Open()
cmd.ExecuteNonQuery()
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
Catch ex As Exception
Finally
cn.Close()
End Try
dt = ds.Tables(0)
'Then return List of string(txtItems) as result
Dim txtItems As New List(Of String)
Dim dbValues As String
For Each row As DataRow In dt.Rows
''String From DataBase(dbValues)
dbValues = row("Test").ToString()
dbValues = dbValues.ToLower()
txtItems.Add(dbValues)
Next
Return txtItems.ToArray()
End Function
End Class
This the coding for the web service we created
AutoComplete.asmx
`<%# WebService Language="vb" CodeBehind="F:\MSDRepairWebDB\App_Data\Errorcode.mdf" Class="AutoComplete" %`>
This is the code for the actual page that using the autocomplete textbox
SearchErrorCode.aspx
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/MasterPage.Master" CodeBehind="SearchErrorCode.aspx.vb" Inherits="MSDRepairWebDB.SearchErrorCode" EnableEventValidation="false" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<h2>
Search Error Code</h2>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx"/>
</Services>
</asp:ToolkitScriptManager>
<asp:AutoCompleteExtender ID="autoComplete1" runat="server"
EnableCaching="true"
BehaviorID="AutoCompleteEx"
MinimumPrefixLength="1"
TargetControlID="tbDGNTestingErrorCode"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
CompletionInterval="0"
CompletionSetCount="10"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
DelimiterCharacters=";, :"
ShowOnlyCurrentWordInCompletionListItem="true">
<Animations>
<OnShow>
<Sequence>
<%-- Make the completion list transparent and then show it --%>
<OpacityAction Opacity="0" />
<HideAction Visible="true" />
<%--Cache the original size of the completion list the first time
the animation is played and then set it to zero --%>
<ScriptAction Script="// Cache the size and setup the initial size
var behavior = $find('AutoCompleteEx');
if (!behavior._height) {
var target = behavior.get_completionList();
behavior._height = target.offsetHeight - 2;
target.style.height = '12px';
}" />
<%-- Expand from 0px to the appropriate size while fading in --%>
<Parallel Duration=".4">
<FadeIn />
<Length PropertyKey="height" StartValue="0"
EndValueScript="$find('AutoCompleteEx')._height" />
</Parallel>
</Sequence>
</OnShow>
<OnHide>
<%-- Collapse down to 0px and fade out --%>
<Parallel Duration=".4">
<FadeOut />
<Length PropertyKey="height" StartValueScript=
"$find('AutoCompleteEx')._height" EndValue="0" />
</Parallel>
</OnHide>
</Animations>
</asp:AutoCompleteExtender>
<tr align=left>
<th class="style2" >
Error Code
</th>
<td>
<asp:TextBox ID="tbDGNTestingErrorCode" autocomplete ="off" runat="server"
Width="190px" MaxLength="5" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="tbDGNTestingErrorCode"
ErrorMessage="Error Code Required!" InitialValue=""
ForeColor="#FF3300"></asp:RequiredFieldValidator>
</td>
</tr>
</asp:Content>
This is the database table structure.
Database : Errorcode.mdf
Table : Errorcode
Can anyone help me to advise to make the auto complete work on the live server?
Thanks

ASP.net datatable is returning no values

i hope you can help with my issue. I'm trying to fill out a form from my database using a datatable. All seems to work fine but i get no data returned. Can anyone explain why? I've looked at the debug and there seems to be no errors and nothing looks like its failed. Here's my code behind (vb.net)
Imports System.Data
Imports System.Data.SqlClient
Imports System.Net.Mail
Partial Class _Default
Inherits System.Web.UI.Page
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim constr As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
Dim connection As New SqlConnection(constr)
connection.Open()
Dim sqlCmd As New SqlCommand("SELECT * from tblContent WHERE CID = #ID", connection)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#ID", Request.QueryString("ID"))
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
ID.Text = dt.Rows(0)("CID").ToString
TextBox2.Text = dt.Rows(0)("Heading").ToString
TextBox1.Text = dt.Rows(0)("ContText").ToString
Label2.Text = dt.Rows(0)("Location").ToString
End If
connection.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
getData(Me.User.Identity.Name)
End If
End Sub
Presentation layer:
<h2><asp:Label ID="Label2" runat="server" Text=""></asp:Label></h2>
<asp:TextBox ID="ID" runat="server" Visible="false"> </asp:TextBox><br />
<asp:Label ID="Label3" runat="server" Text="Heading" CssClass="label"></asp:Label>
<asp:TextBox ID="TextBox2" TextMode="SingleLine" Text="" runat="server"></asp:TextBox><br />
<asp:Label ID="Label1" runat="server" Text="Content" CssClass="label"></asp:Label><br />
<asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server"></asp:TextBox>
I'm passing through the ID from another page via the query string (ID=5 as an example). There is data in my database and all labels/textboxes have the right IDs etc. I just can see what's wrong?
Thanks!
You could try to pass the correct type instead of string:
Using sqlDa As New SqlDataAdapter(sqlCmd)
Dim idParam = new SqlParameter("#ID", SqlDbType.Int)
Dim id As Int32
If Not Int32.TryParse(Request.QueryString("ID"), id) Then Throw New Exception("Not a valid ID-parameter!")
idParam.Value = id
sqlDa.SelectCommand.Parameters.Add(idParam)
sqlDa.Fill(dt)
End Using
By the way, also use the Using-statement for the connection. As an aside, you don't need to open/close the connection with SqlDataAdapter.Fill(table) since that is done automatically.

vbCode is autocomplete is not working

I am new to VB.net I want get list of names from my DB with auto complete. I am trying to follow the following example.
But My problem is it not working and I was not getting any error can any one tell me where I am doing wrong.
My home.aspx
<%# Page Title="Home Page" Language="VB" CodeFile="~/home.aspx.vb" AutoEventWireup="true" Inherits="_home"%>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ScripManager1" runat="server"/>
<asp:UpdatePanel ID="autoupdate" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server"
TargetControlID="txtSearch" ServiceMethod="GetList" MinimumPrefixLength="3"
UseContextKey="True" >
</asp:AutoCompleteExtender>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
This is my home.aspx.vb
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Threading
Imports System.Web.Services
Partial Class _Default
Inherits System.Web.UI.Page
<WebMethod()> _
Public Shared Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer, ByVal contextKey As String) As String()
Try
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Test").ConnectionString)
con.Open()
Dim cmd As New SqlCommand("select LoginName from users where LoginName like '#Name' +'%' ", con)
cmd.Parameters.AddWithValue("#Name", prefixText)
'Dim da As New SqlDataAdapter(cmd)
'Dim dt As New DataTable()
'da.Fill(dt)
'Dim InviteSearchListresult As New List(Of String)()
'For i As Integer = 1 To dt.Rows.Count
' InviteSearchListresult.Add(dt.Rows(i)(1).ToString())
' Next
Dim result As New List(Of String)()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
result.Add(dr("LoginName").ToString())
End While
Return (
From m In result
Where m.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase)
Select m).Take(count).ToArray()
Catch ex As Exception
End Try
End Function
End Class
Please help how to solve this issuse.
Your service method is GetList but your actual method name is GetCompletionList.
Try getting the method names to match up and see if that's the problem. You're trying to call a method that doesn't exist.

Can the results of my search be links to pages?

I have a search engine on my ASP.net 4.0 VB site that in which I need to link the search results with their individual pages. I understand that this can be done simply with a submit button after the search textbox but a submit button wouldn't fit next to the search bar on my page, plus it wouldn't look right.
The old way, the results were stored in a hidden div where they became links to their pages. I was hoping that the code I have of the old search could be incorporated into the new search, but I do not know where it would go. The only way I can think of to do it is to place the code in the webservice in a while or for loop. I may be way off base here, but that is why I am asking what the best way to go about this would be?
<WebMethod()> _
Public Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer) As String()
Dim ProductSql As String = "Select ProductName FROM Product WHERE ProductName LIKE '" & prefixText & "%'"
Dim sqlConn As New SqlConnection
sqlConn.Open()
Dim myCommand As New SqlCommand(ProductSql, sqlConn)
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
Dim myTable As New DataTable
myTable.TableName = "ProductSearch"
myTable.Load(myReader)
sqlConn.Close()
Dim items As String() = New String(myTable.Rows.Count - 1) {}
Dim i As Integer = 0
For Each dr As DataRow In myTable.Rows
items.SetValue(dr("ProductName").ToString(), i)
i += 1
Next
Return items
End Function
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="ProductSearch.asmx" />
</Services>
</asp:ScriptManager>
<asp:TextBox ID="Search" runat="server" AutoComplete="off"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="Search" ServicePath="~/ProductSearch.asmx" ServiceMethod="GetCompletionList" MinimumPrefixLength="1" CompletionSetCount="120" EnableCaching="true" CompletionListCssClass="results">
</asp:AutoCompleteExtender>
I used a little javascript to make links out of the results of my search engine query. This is what I have now - although the For Each loop in the Web Service doesn't work properly.
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript">
function AutoCompleteClientMethod(source, eventArgs) {
var value = eventArgs.get_value();
window.location = ("/Product/Default.aspx?id=" + value)
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="ProductSearch.asmx" />
</Services>
</asp:ScriptManager>
<asp:TextBox ID="Search" runat="server" AutoComplete="off"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="Search" ServicePath="~/ProductSearch.asmx" ServiceMethod="GetProducts" MinimumPrefixLength="1" CompletionSetCount="120" EnableCaching="true" OnClientItemSelected="AutoCompleteClientMethod">
</asp:AutoCompleteExtender>
</asp:Content>
<WebMethod()> _
Public Function GetProducts(ByVal prefixText As String, ByVal count As Integer) As String()
Dim ProductSql As String = "Select ProductID, ProductName FROM Product WHERE ProductName LIKE '" & prefixText & "%'"
Dim sqlConn As New SqlConnection
sqlConn.Open()
Dim myCommand As New SqlCommand(ProductSql, sqlConn)
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
Dim myTable As New DataTable
myTable.TableName = "ProductSearch"
myTable.Load(myReader)
sqlConn.Close()
Dim items As String() = New String(myTable.Rows.Count - 1) {}
Dim i As Integer = 0
For Each dr As DataRow In myTable.Rows
items.SetValue(dr("ProductName").ToString(), i)
i += 1
Next
Return items
End Function
End Class

Resources