I am looking for good example how I can implement Bootstrap Typeahead with asp.net Webforms application.
The application is using Bootstrap theme already and various plugins. Now I want the user to be able to search through dataset with minimum three letters entered. Once the user will enter three letters the script will be triggered to start searching for values matching the entered word through web method and then deliver the results to the user.
From the examples I saw so far on the net I have this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> GetNames(string term)
{
// A list of names to mimic results from a database
List<string> nameList = new List<string>
{
"Jonathan", "Lisa", "Jordan", "Tyler", "Susan", "Brandon", "Clayton", "Elizabeth", "Jennifer"
};
var results = nameList.Where(n =>
n.StartsWith(term, StringComparison.OrdinalIgnoreCase));
return new JsonResult()
{
Data = results.ToArray(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
At the code chunk above JsonResult() and JsonRequestBehavior are not recognized and I am getting errors. Then on client side I have this:
<input type="text" id="txtSearch" data-provide="typeahead" runat="server" />
Then the script I have this (also found online):
<script type="text/javascript">
$(document).ready(function () {
$('#<%= txtSearch.ClientID %>').typeahead({
source: function (query, process) {
},
updater: function (item) {
// implementation
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp( '(' + this.query + ')', 'gi' );
return item.replace( regex, "<strong>$1</strong>" );
},
});
});
</script>
try this
<input type="text" id="txtSearch" data-provide="typeahead" runat="server" />
//No javascript only add bootstrap.js or typeahead js and css
protected void Page_Load(object sender, EventArgs e)
{
List<string> nameList = new List<string>
{
"Jonathan", "Lisa", "Jordan", "Tyler", "Susan", "Brandon", "Clayton", "Elizabeth", "Jennifer"
};
string str = "";
for (int i = 0; i < nameList.Count; i++)
{
str = str + '"' + nameList[i].ToString() + '"' + ',';
}
if (str != "")
{
str = str.Remove(str.Length - 1);
}
str = "[" + str + "]";
txtSearch.Attributes.Add("data-source", str);
}