1

I have been having trouble with an auto-complete (from database) textbox. It makes an ajax call to a WebMethod in an ASP.NET (VB) webpage, and gives me an "Authentication Error" whenever a letter is typed in the textbox.

The aspx page code is as follows:

<body>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script language="javascript" type="text/javascript">
        $(function () {
            $('#<%=txtCompanyName.ClientID%>').autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '<%= ResolveUrl("VendorList.aspx/GetCompanyName")%>',
                data: "{ 'pre':'" + request.term + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data.d, function (item) {
                        return { value: item }    
                    }))
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest.responseText);
                }
            });
        }
        });
        });
    </script>
    <div class="ui-widget" style="text-align:left">
        <asp:TextBox ID="txtCompanyName" runat="server" Width="350px" CssClass="textboxAuto"  Font-Size="12px" />
    </div>
</body>

The VB.NET code behind file code is as follows:

Partial Class VendorList

<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod(ResponseFormat:=Script.Services.ResponseFormat.Json)> _
Public Shared Function GetCompanyName(ByVal pre As String) As List(Of String)
    Dim allCompanyNames As New List(Of String)
    Using myEntities As New VendorEntities()
        allCompanyNames = (From vendor In myEntities.Vendors
                           Where vendor.VendorName.StartsWith(pre)
                           Select vendor.VendorName).ToList()
    End Using
    Return allCompanyNames
End Function

End Class

I have also tried to create a Web.config file in the directory that this page is contained in, with the following code:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>

I am also using FriendlyURLS.

Any ideas on how to get around this Authentication error? Thanks


Update

I now have also tried the AjaxControlToolkit AutoCompleteExtender, but I am only getting back a list of the HTML markup for the page, with one character per list item.

The code for the aspx page is as follows:

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true"></asp:ScriptManager> 
    <asp:TextBox ID="txtVendorNameSearch" runat="server"></asp:TextBox>
            <cc1:AutoCompleteExtender
                MinimumPrefixLength="2" ServiceMethod="SearchVendorNames"
                CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
                TargetControlID="txtVendorNameSearch" 
                ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
            </cc1:AutoCompleteExtender>

</asp:Content>

The code for the VB.NET code behind file is as follows:

Partial Class Operations_Inventory_AutoCompleteTest
    Inherits BasePage

    <System.Web.Script.Services.ScriptMethod(), _
    System.Web.Services.WebMethod()> _
    Public Function SearchVendorNames(ByVal prefixText As String, ByVal count As Integer) As List(Of String)

        Dim vendorNames As List(Of String) = New List(Of String)
        Using myEntities As New VendorEntities()
            Dim vendors = (From vendor In myEntities.InventoryVendors
                           Where vendor.VendorName.StartsWith(prefixText)
                           Select vendor.VendorName, vendor.ID).ToList()


            For Each item In vendors
                vendorNames.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(item.VendorName, item.ID.ToString))
            Next
        End Using
        Return vendorNames
    End Function
End Class
J2Tuner
  • 411
  • 1
  • 5
  • 17
  • this help? -- [How to use Basic Auth](http://stackoverflow.com/a/5507289/5090771) -- or -- [Using Authentication with Ajax.Request](http://stackoverflow.com/a/3299127/5090771) – WhiteHat Dec 29 '15 at 18:44
  • In reality, you don't need authentication access as long as the url you're trying to call is within the same webserver. – DinoMyte Dec 29 '15 at 18:45
  • @WhiteHat - I am unsure of what to use for the username and password here. Is there not a way to allow this to be anonymous? – J2Tuner Dec 29 '15 at 19:04
  • @DinoMyte - The URL is on the same webserver. In fact, if I change the URL from VendorList.aspx to just VendorList, I get a "parseerror" and the XMLHttpRequest.responseText returns client side page markup... – J2Tuner Dec 29 '15 at 19:07
  • are there more details to the error? – WhiteHat Dec 29 '15 at 19:08
  • Check this : http://stackoverflow.com/questions/20032240/authentication-failed-during-call-webmethod-from-jquery-ajx-with-aspnet-friendly – DinoMyte Dec 29 '15 at 19:09
  • @WhiteHat - {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"} – J2Tuner Dec 29 '15 at 19:11
  • @DinoMyte - I do not have a App_Start folder or a RouteConfig file configured in this application. Is this something I should create? Or can this be handled by the Global.asax file? Is App_Start only for ASP MVC applications? – J2Tuner Dec 29 '15 at 19:12
  • App_start is a global method invoked in Global.asax for all asp.net web applications. Have you tried attaching attribute [System.Web.Script.Services.ScriptService] to your webmethod ? – DinoMyte Dec 29 '15 at 19:22
  • @DinoMyte - I did just try, but I got the following VS2013 intellisense error: "Attribute 'ScriptServiceAttribute' cannot be applied to 'GetCompanyName' because the attribute is not valid on this declaration type." – J2Tuner Dec 29 '15 at 19:54

2 Answers2

0

Try using Ajax AutoCompleteExtender

Your WebMethod should change like below:

You should return something like below

List<string> items = new List<string>();
        foreach (var companyName in allCompanyNames)
            items.Add(AutoCompleteExtender.CreateAutoCompleteItem(companyName["VendorName"], companyName["ID"].ToString());

        return items;

I hope you select the ID of company name as well in your LINQ query.

 allCompanyNames = (From vendor In myEntities.Vendors
                       Where vendor.VendorName.StartsWith(pre)
                       Select vendor.VendorName, vendor.ID).ToList()
techspider
  • 3,370
  • 13
  • 37
  • 61
  • I did try this, and it seems like it is trying to work, but it is netting a similar result as when I changed the URL above to VendorList from VendorList.aspx. It is giving me a drop down list as I type, but it contains a list of the entire client side html mark-up, instead of my database query results. I did try this both with a standard SQL connection and an Entities connection, and they produced the same result. Do you have any ideas what could be causing this? – J2Tuner Dec 29 '15 at 21:24
  • I cannot find the CreateAutoCompleteItem method of the AutoCompleteExtender. Did this change? – J2Tuner Dec 29 '15 at 22:00
  • did you add using AjaxControlToolkit; at the top; it is available in 15.1.4.0 afaik – techspider Dec 29 '15 at 22:01
  • this might be helpful for you http://www.aspsnippets.com/Articles/Fetch-multiple-values-as-Key-Value-pair-in-ASP.Net-AJAX-AutoCompleteExtender.aspx – techspider Dec 29 '15 at 22:02
  • I was able to find the CreateAutoCompleteItem method now, as I was not using the AjaxControlToolKit class before. I am still having the exact same issue though, and I have updated the post with the new code that I have tried. It is from a very similar post to your previously mentioned link. http://www.aspsnippets.com/Articles/AJAX-AutoCompleteExtender-Example-in-ASPNet.aspx – J2Tuner Dec 29 '15 at 22:32
0

Adding

beforeSend: function (xhr) { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); },

Worked for my error.

$.ajax({ 
    type: 'POST',
    beforeSend: function (xhr) { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); },
    contentType: "application/json; charset=utf-8",
Tunaki
  • 132,869
  • 46
  • 340
  • 423