Kroneaux Schneider
Kroneaux Schneider

Reputation: 294

Twitter's Typeahead is not working

I'm working on an MVC project with C# and I need a search engine. Google tells me to use Twitter's Typeahead so I'm trying to make things work but it simply does not, even whit the simplest

<input id="search" />

@section Script{
    <script src="~/Scripts/typeahead.jquery.js"></script>
    <script src="~/Scripts/typeahead.bundle.js"></script>
    <script>
        var colors = ["red", "blue", "green", "yellow", "brown", "black"];

        $('#search').typeahead({ source: colors });
    </script>
}

This code leads to nothing, just an input on the page that triggers nothing. You might tell me to watch the console but it's blank. I'm losing my mind with this! I even tried to install it directly from NuGet but the result is just the same: nothing happens.

Tried so far:

Upvotes: 1

Views: 392

Answers (1)

Kroneaux Schneider
Kroneaux Schneider

Reputation: 294

Well, after some research, I found jQuery Autocomplete which worked since the first time, so here's the code I finally used:

/// <summary>
/// Obtiene el JSON de resultados de búsqueda.
/// </summary>
/// <param name="query">Búsqueda.</param>
/// <returns></returns>
[HttpGet, Authorize]
public ContentResult getAll(string query)
{
    DataTable dt;
    List<Models.Global.ISearchResult> _l = new List<Models.Global.ISearchResult>();
    dt = ...
    foreach (DataRow dr in dt.Rows)
    {
        _l.Add(new Models.Global.ResultadosContratistasModel()
        {
            value = dr["NAME"].ToString(),
            Url = "/Account/{0}".Write(dr["ACCOUNTNUM"])
        });
    }
    ...
    return Content(JsonConvert.SerializeObject(new { suggestions = _l }), "application/json");
}

using this data model:

public interface ISearchResult
{
    string value { get; set; }
    string Categoría { get; }
    string Url { get; set; }
    ISearchResultData data { get; }
}
public interface ISearchResultData
{
    string category { get; set; }
    string goTo { get; set; }
}

/// <summary>
/// objeto "data" del resultado de búsqueda rápida.
/// </summary>
[DataContract]
public struct SearchResultData : ISearchResultData
{
    /// <summary>
    /// Categoría de la respuesta.
    /// </summary>
    [DataMember]
    public string category { get; set; }
    /// <summary>
    /// Url a la que dirigirá el resultado.
    /// </summary>
    [DataMember]
    public string goTo { get; set; }
}

/// <summary>
/// Clase serializable de Resultados de búsqueda rápida de obra.
/// </summary>
[DataContract]
public class ResultadosObraModel : ISearchResult
{
    /// <summary>
    /// Texto a mostrar como resultado de la búsqueda.
    /// </summary>
    [DataMember]
    public string value { get; set; }
    /// <summary>
    /// Categoría del resultado de búsqueda.
    /// </summary>
    [IgnoreDataMember]
    public string Categoría
    {
        get
        {
            return "Obras";
        }
    }
    /// <summary>
    /// URL a la que deberá dirigirse si se selecciona la opción.
    /// </summary>
    [IgnoreDataMember]
    public string Url { get; set; }
    /// <summary>
    /// Objeto "data" con la información requerida por el plugin.
    /// </summary>
    [DataMember]
    public ISearchResultData data
    {
        get{
            return new SearchResultData()
            {
                category = Categoría,
                goTo = Url
            };
        }
    }
}

and on the JS side:

$('input#goBox').autocomplete({
    serviceUrl: '/consultas/getAll',
    minChars: 2,
    lookupLimit: 10,
    groupBy: 'category',
    noSuggestionNotice: 'Presiona "Enter" para ver más resultados.',
    onSelect: function (suggestion) {
        location.href = suggestion.data.goTo;
    }
});

I hope somebody will find this helpful!

Upvotes: 0

Related Questions