我使用Jquery在文本框中进行了自动完成,如下所示:
$(document).ready(function () {
$('#searchCollabo').autocomplete({
source: '@Url.Action("AutocompleteCollabo")'
});
});
所以数据来自 AutocompleteCollabo 方法,如下所示:
public ActionResult AutocompleteCollabo(string term)
{
int NumDossier = StructureData.DonneNumDossier((string)Session["NumCRPCEN"], (string)Session["MotDePasse"]);
List<Contact> ListeContacts = StructureData.DonneListeElementDossier(NumDossier);
Contact[] tabContacts = new Contact[ListeContacts.Count()];
int count = 0;
foreach (Contact contact in ListeContacts)
{
tabContacts[count] = contact;
count++;
}
var collaborateurs = tabContacts;
var collaborateurFiltres = collaborateurs.Where(
item => item.Nom.Contains(term) || item.Fonction.Contains(term)
);
return Json(collaborateurFiltres, JsonRequestBehavior.AllowGet);
}
返回的json包含一个对象列表,如下所示:
[{"ListeFonctions":[],"IdContact":91264,"Nom":"solecki","Prenom":"hubert","Email":"hsolecki@mail.c"}]
现在我想设置显示名称(名称+功能)以及当我选择一行自动完成时我想要获得的值。你有想法吗?
答案 0 :(得分:0)
我发现了怎么做,这可能有所帮助。 我通过Ajax调用调用的函数:
public ActionResult AutocompleteCollabo(string term)
{
int NumDossier = StructureData.DonneNumDossier((string)Session["NumCRPCEN"], (string)Session["MotDePasse"]);
List<Contact> ListeContacts = StructureData.DonneListeElementDossier(NumDossier);
var tabContactFull = ListeContacts.Where(contact => contact.Nom.Contains(term) || contact.Prenom.Contains(term) || contact.Fonction.Contains(term));
var tabInfosUtiles = tabContactFull.Select(contact => new { label = contact.Nom + " " + contact.Prenom + " ("+contact.Fonction+") ", value = contact.Nom + " " + contact.Prenom + " ("+contact.Fonction+") ", id = contact.IdContact }).ToArray();
// We set our needed informations with a title like "Label", "Value"
// So the auto-complete can find by itself which data to display and which are for the value
return Json(tabInfosUtiles, JsonRequestBehavior.AllowGet);
}
我的Ajax调用和成功事件:
$(document).ready(function () {
$('#searchCollabo').autocomplete({
source: '@Url.Action("AutocompleteCollabo")',
select: function (event, ui) {
$("#idElement").val(ui.item.id);
// If you want to get the value : ui.item.Value
// If you want to get the label : ui.item.Label
}
});
});
希望对大家有所帮助!