What you’re looking for is called Typeahead.
Usually the solution does not come alone: it accompanies another framework, like Bootstrap. There are some implementations of Typeahead for Bootstrap:
Or using only jQuery:
Depending on the implementation you choose, there may be a different Ajax format, usually asking for JSON. For these cases, implement a Action in Controller return JSON:
public JsonResult ActionQueTrabalhaComTypeAhead()
{
var exemplo = new String[] { "1", "2", "3" };
return Json(exemplo, JsonRequestBehavior.AllowGet);
}
I don’t know what you’re using to bring information from the bank, but I’ll assume it’s the Entity Framework.
In case, let’s assume that you are bringing names of people and their respective Id’s (like the first example here, only with people instead of states). First let’s assemble 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 of 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);
}
https://jqueryui.com/autocomplete/ da uma olhada :), ja q o mvc ja tem jquery msm
– Lucas
@Ciganomorrisonmendez is just like this, only it has to implement it to pull the data from a table in the database ?
– Leonardo Macedo
Yes, see my answer. If anything is missing, just say so by comment.
– Leonel Sanches da Silva