What you are looking for is called Typeahead .
Normally the solution does not come by itself: it comes with another framework , such as Bootstrap. There are some implementations of Typeahead for Bootstrap:
Or just using jQuery:
Depending on the implementation you choose, there may be a different Ajax format, usually requesting JSON. For these cases, implement an Action on Controller that returns JSON:
public JsonResult ActionQueTrabalhaComTypeAhead()
{
var exemplo = new String[] { "1", "2", "3" };
return Json(exemplo, JsonRequestBehavior.AllowGet);
}
I do not know what you're using to bring information from the database, but I'll assume it's the Entity Framework.
In this case, let's say you're bringing people's names and their Id's ( same as the first example here < a>, but with people instead of states). First let's set up the presentation. It should contain something like this:
<div id="exemplo">
<input class="typeahead" type="text" id="typeaheadpessoas" placeholder="Nomes de Pessoas">
</div>
Typeahead works with a prediction engine called Bloodhound. It can be configured like this:
window.pessoas = new Bloodhound({
identify: function (obj) { return obj.Descricao; },
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.Descricao);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
ttl: 0,
url: '@Url.Action("PreCargaTypeAhead", "Pessoas")'
},
remote: {
url: '@Url.Action("ActionQueTrabalhaComTypeAhead", "Pessoas")',
replace: function (url, uriEncodedQuery) {
return url + '?termo=' + uriEncodedQuery;
}
}
});
window.pessoas.initialize();
window.typeahead_pessoas_data = {
name: 'pessoas',
displayKey: 'Descricao',
source: window.pessoas,
limit: 10,
templates: {
empty: [
'<div class="typeahead-empty-message">',
'Não encontrado',
'</div>'
].join('\n')
}
};
window.typeahead_options = {
hint: true,
highlight: true,
minLength: 3
};
$('#typeaheadpessoas').typeahead(window.typeahead_options, typeahead_pessoas_data
).on('typeahead:selected', function (event, data) {
// Faça alguma coisa aqui com data. Data é um json.
});
An example data search:
[HttpGet]
public async Task<JsonResult> ActionQueTrabalhaComTypeAhead(String termo)
{
if (String.IsNullOrEmpty(termo)) return Json(null, JsonRequestBehavior.AllowGet);
// Aqui faço a pesquisa ao banco de dados.
// Pesquiso ou pelo nome da pessoa ou pelo seu CPF.
var pessoas = await db.Pessoas.Where(r => r.Nome.Contains(termo) || r.Cpf.Contains(termo)).ToListAsync();
return Json(pessoas.Select(p => new
{
PessoaId = p.PessoaId,
Descricao = p.Nome + " - " + p.Cpf
}), JsonRequestBehavior.AllowGet);
}