Rich
Rich

Reputation: 1915

Querying a remote datasource with jQuery Autocomplete

Im trying to implement an asp.net textbox using the jQuery UI Autocomplete widget http://jqueryui.com/demos/autocomplete/#remote.

The source property of the widget expects a string to point to a URL resource that will return JSON data. I have an aspx page that will return the following:

Code Behind:

private void GetWidgets(string name)
{
    var jscriptSerializer = new JavaScriptSerializer();
    var widgets = jscriptSerializer.Serialize(GetMatchingWidgets(name));
    var script = "Widgets = {\"Widget\": " + widgets + "};";

    Page.ClientScript.RegisterStartupScript(Page.GetType(), "JSON", script, true);
}

Questions:

  1. The documentation says the The request parameter "term" gets added to that URL. -- I should therefore be able to get the "term" as a query string parameter correct?
  2. Do I have to set the JSON to a variable on the client or does the widget take care of the binding without having to do anything else?

Am I missing anything else?

I would give this a try and just "figure it out" but I don't have a whole lot of time to spend on this solution.

Help is always appreciated.

Upvotes: 1

Views: 658

Answers (1)

dotjoe
dotjoe

Reputation: 26940

Yes, term is the name of the QueryString parameter. All you need to do is return json data in the expected format. For example, here is the class I use...

/// <summary>
/// JQuery UI Autocomplete plugin expects an object with "value" and/or "label" property.
/// </summary>
public class AutoCompleteData
{
    /// <summary>
    /// custom property
    /// </summary>
    public string id { get; set; }

    /// <summary>
    /// value is shown in text box after selection
    /// </summary>
    public string value { get; set; }

    /// <summary>
    /// label is shown in drop down list
    /// </summary>
    public string label { get; set; }
}

for example...

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

AutoCompleteData[] d = GetMatchingWidgets(term)
    .Select(x => new AutoCompleteData {
        label = x.widgetLabel,
        value = x.widgetValue
    }).ToArray();

return jscriptSerializer.Serialize(d);

Upvotes: 1

Related Questions