I have implemented an autocomplete using Twitter typeahead (with Bloodhound engine) and it runs fine. My next step is to use the generated/obtained data (in my case 'name' and 'id') to do a search operation. This is where I am having difficulty.I'm completely blank regarding how to pass the data to the controller for a search operation. I'm not using form but I wanna use either Search button click or a js function OnclickSearchButton or may be there is a better way?!
My JS code:
$(document).ready(function () {
var viewModel = {}; //will store id and string to pass for the search operation
//var urlRoot = '/Test/GetName';
//we get url to the controller and min. char to invoke search from the html helper JavaScriptParameter
var urlRoot = urlToController;
//var lengthMin = 1;
var lengthMin = minCharNeededForSearch;
var information = {
url: urlRoot,
prepare: function (query, settings) {
settings.type = "POST",
settings.url += '?prefix=' + query;
return settings;
}
};
var names = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('navn'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: information,
});
//options
$('#search').typeahead({
hint: false,
minLength: lengthMin,
highlight: true,
},
//dataset
{
name: 'navn', //The name of the dataset
display: 'name', // For a given suggestion, determines the string representation of it. This will be used when setting the value of the input control after a suggestion is selected.
source: names, //the backing data source for suggestions
limit: 10 //this is bug fix-around in Bloodhound engine so that it displays more than 1 or 2 record in the autocomplete
}).on("typeahead:selected", function (e, datum) {
//console.log(datum);
//not sure if I can write a function here
$('.search').on("click", function () {
$.ajax({
type: 'POST',
url: '/Test/GetResponse',
data: datum,
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("click function working");
}
});
});
});
});
My corresponding HTML:
<div class="input-group"><span class="searchInfoImage"></span><input class="form-control fri ui-autocomplete-input" id="search" placeholder="search here..." style="min-width:175px" type="text"></input><button caption="search" class="btn btn-basic-blue search" click="OnclickSearchButton()" type="button">Search</button></div>
My asp.net controller's method:
[HttpPost]
public JsonResult GetName(string prefix)
{
var names = (from n in context.checkboxstates
where n.Navn.StartsWith(prefix)
select new
{
name = n.Navn,
Id = n.Id
}).ToList();
return Json(names);
}
Your help will be highly appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…