Search code examples
c#jqueryasp.netajaxtypehead

Unable to return typehead.js with asp.net and ajax


I am trying to return my query as a user enters in information. However when I enter data into the textbox it returns an HTML popup page with random HTML code. I can figure out why the ajax callback isn't finding the [webmethod] as I think this may be the issue.

Default.aspx code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
    <title>testing typescript</title>
<link rel="stylesheet" href='http://cdnjs.cloudflare.com/ajax/libs/twitter-   bootstrap/3.0.3/css/bootstrap.min.css'
media="screen" />
<script type="text/javascript" src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js'></script>
<script type="text/javascript"   src='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
<script type="text/javascript" src="http://cdn.rawgit.com/bassjobsen/Bootstrap-3-Typeahead/master/bootstrap3-typeahead.min.js"></script>
<link rel="Stylesheet" href="https://twitter.github.io/typeahead.js/css/examples.css" />
<script type="text/javascript">
$(function () {
    $('[id*=txtSearch]').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
        , source: function (request, response) {
            $.ajax({
                url: '<%=ResolveUrl("/Default.aspx.cs/GetCustomers") %>',
                data: "{ 'prefix': '" + request + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    items = [];
                    map = {};
                    $.each(data.d, function (i, item) {
                        var id = item.split('-')[1];
                        var name = item.split('-')[0];
                        map[name] = { id: id, name: name };
                        items.push(name);
                    });
                    response(items);
                    $(".dropdown-menu").css("height", "auto");
                },
                error: function (response) {
                    alert(response.responseText);
                },
                failure: function (response) {
                    alert(response.responseText);
                }
            });
        },
        updater: function (item) {
            $('[id*=hfCustomerId]').val(map[item].id);
            return item;
        }
    });
});
</script>
</head>
<body>
Enter search term:
<form runat="server">
<asp:TextBox ID="txtSearch" runat="server" CssClass="form-control"  autocomplete="off"
 Width="300"/>
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />
</form>
     </body>
</html>

Default.aspx.cs (code behind file)

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

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Submit(object sender, EventArgs e)
{
    string customerName = Request.Form[txtSearch.UniqueID];
    string customerId = Request.Form[hfCustomerId.UniqueID];
    ClientScript.RegisterStartupScript(this.GetType(), "alert",  "alert('Name: " + customerName + "\\nID: " + customerId + "');", true);
}

[WebMethod]

public static string[] GetCustomers(string prefix)
{
    List<string> customers = new List<string>();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = "<%$ ConnectionStrings:FormDataConnectionString %>";
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT [ID], [name], FROM [Wireless_Order]  where ContactName like @SearchText + '%'";
            cmd.Parameters.AddWithValue("@SearchText", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(string.Format("{0}-{1}", sdr["name"], sdr["ID"]));
                }
            }
            conn.Close();
        }
    }
    return customers.ToArray();
  }
 }

I have included this in my web.config file

 <system.web>
  <pages clientIDMode="Static"></pages>
  <compilation debug="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />
  <webServices>
    <protocols>
      <add name="HttpGet"/>
      <add name="HttpPost"/>
    </protocols>
  </webServices>

</system.web>

Solution

  • The issue was here.

    /Default.aspx.cs/GetCustomers
    

    Needed to be

    Default.aspx/GetCustomers
    

    to find the file.

    Still get an error though when I click the backspace to clear the textfield.