1

I'm trying to implement a simple WebMethod in C# to search a db of 50,000 people. I'm using Twitter Bootstrap bloodhound.js and typeahead.js to tokenize and autocomplete the responses.

When I run this code, typeahead shows a dropdown menu with undefined.

How can I correctly process the JSON response to strip out the d object returned by .NET WebMethod and correctly pass my records to Bloodhound? I've tried this using the dataFilter method provided by jQuery's $.ajax, but it's not working for me.

C# WebMethod:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object searchStaffByName(string q)
{
    using (App_Data.DQDBDataContext dc = new App_Data.DQDBDataContext())
    {
        var results = dc.getStaffDetails(q).ToList();
        return new { Status = "OK", Records = results, Count = results.Count }; 
    }
}

Typeahead JS implementation:

var textlookup = new Bloodhound({
    datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.val);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: 'Search.aspx/searchStaffByName',
        replace: function (url, query) {
            searchQuery = query;
            return url;
        },
        ajax: {
            beforeSend: function (jqXhr, settings) {
                settings.data = JSON.stringify({
                    q: searchQuery
                });
                jqXhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
            },
            dataFilter: function (data, type) {
                if (type === "json") {
                    data = $.parseJSON(data);
                    if (typeof data.d === 'object' && data.d.Count > 0) {
                        return data.d.Records;
                    }
                }
            },
            type: 'POST'
        }
    }
});

textlookup.initialize();

$('.autocomplete').typeahead({
    hint: true,
    highlight: true,
    minLength: 3
},
{
    name: 'textlookup',
    displayKey: 'Forename',
    source: textlookup.ttAdapter()
});

Sample JSON Response:

{
    "d": {
        "Status":"OK",
        "Records": [{
            "id":45711192,
            "phone":"514-579-5721",
            "Forename":"Jayden",
            "Surname":"Adams",
            "DOB":"\/Date(990226800000)\/"
        },
        {
            "id":12603644,
            "phone":"333-143-9094",
            "Forename":"Jake",
            "Surname":"Adams",
            "DOB":"\/Date(43542000000)\/"
        },
        {
            "id":68196438,
            "phone":"440-505-2403",
            "Forename":"Josh",
            "Surname":"Adams",
            "DOB":"\/Date(-51152400000)\/"
        }],
        "Count":6
    }
}
Adam
  • 1,932
  • 2
  • 32
  • 57
  • I'd double check what `data` actually is after you parse it, then make sure you are getting into your `if` block. – Jack Aug 14 '14 at 14:19

2 Answers2

1

If your typeahead data will be in the name: 'textlookup', array, populate the array with your JSON response first. The following assumes data is the JSON.

textlookup = [];
    for (var i = 0; i < data.d.Records.length; i += 1) {
       textlookup.push(data.d.Records[i].Forename);
}

This should push each Forename into the array textlookup. You are getting the undefined error because you are placing objects into the array.

Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78
1

I spent some time on this and found that it's better to return a an string array. Here's my web method.

    [WebMethod]
    public static string[] MemberLookup(string MbrFullName)
    {

        DataSet ds = (dataset provider goes here)

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

        foreach(DataRow dr in ds.Tables[0].Rows)
        { members.Add(string.Format("{0}-{1}", dr["label"].ToString(), dr["value"].ToString())); }
        return members.ToArray();
    }