如何设置显示值和自动完成文本框的值

本文关键字:文本 设置 显示 何设置 | 更新日期: 2023-09-27 18:30:57

我使用 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"}]

现在我想设置显示名称(名称+函数)和选择自动完成行时要获得的值。你有什么想法吗?

如何设置显示值和自动完成文本框的值

我找到了如何做到这一点,它可能会有所帮助。我通过 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
        }
    });
});

希望对你们中的一些人有所帮助!