0

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

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

4

1 回答 1

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
        }
    });
});

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

于 2013-09-16T10:28:46.130 回答