jquery自动完成传递参数

时间:2017-05-23 13:01:04

标签: asp.net-mvc jquery-ui autocomplete active-directory

我需要帮助通过JQuery的自动完成传递参数。我有一个输入:

<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" name="searchName" id="searchName" placeholder="Nom et/ou prénom" />

在表单中。键入时,jquery自动完成功能会在Active Directory中启动搜索并在下拉列表中显示结果:

    $(document).ready(function () {
        $("#searchName").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/SearchUserWhileTyping",
                    type: "GET",
                    data: { name: $("#searchName").val() },
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        $("#searchName").html(''),
                        response($.map(data, function (item) {
                            return {
                                label: item
                            }
                        }));
                    }
                });
            },
            minLength: 4
        })
    });
    $(document).ready(function(){
        $('#searchName').on('autocompletechange change', function () {
                $('#searchValue').html('You selected: ' + this.value);
            }).change()});

目前我只能在表单验证后执行此操作:表单已验证 - &gt;我加载了找到的用户和他们唯一的ID - &gt;点击一个链接,它会显示用户信息,这要归功于他们传递的唯一ID。我想要做的是:如果您点击其中一个自动填充选项,它会直接显示您的用户信息。

以下是您键入内容时的搜索代码:

[HttpGet]
    public ActionResult SearchUserWhileTyping(string name)
    {
        ADManager adManager = new ADManager();
        List<string> lastName = adManager.SearchUserByName(name);
        List<string> splitList = new List<string>();
        if (lastName != null)
        {
            if (lastName.Count <= 10)
            {
                int inc = 0;
                foreach(string splitter in lastName)
                {
                    if (inc % 2 == 1)
                    {
                        splitList.Add(splitter);
                    }
                    inc++;
                }
                return Json(splitList, JsonRequestBehavior.AllowGet);
            }
        }
        return null;
    }

我使用分割器,因为另一个函数允许我搜索AD并返回几个参数(这将有助于通过其唯一ID立即找到用户,这是我的难度)。 这会调用以下函数:

public List<string> SearchUserByName(string name)
        {
            try
            {
                DirectoryEntry ldapConnection = createDirectoryEntry();
                DirectorySearcher search = new DirectorySearcher(ldapConnection);
                var sidInBytes=new byte[0];
                //anr permet de chercher tout utilisateur contenant "name"
                search.Filter = "(&(objectClass=user)(anr=" + name + "))";
                //search.Filter = "(&(objectClass=User) (name=" + name + "*))";
                search.PropertiesToLoad.Add("displayName");
                search.PropertiesToLoad.Add("distinguishedName");
                resultCollection = search.FindAll();

                if (resultCollection.Count == 0)
                {
                    return null;
                }
                else
                {
                    foreach(SearchResult sResult in resultCollection)
                    {
                        if (sResult.Properties["distinguishedName"][0].Equals(null) ||
                            sResult.Properties["displayName"][0].Equals(null))
                            continue;

                        displayName.Add(sResult.Properties["distinguishedName"][0].ToString());
                        displayName.Add(sResult.Properties["displayName"][0].ToString());
                    }
                }
                ldapConnection.Close();
                ldapConnection.Dispose();
                search.Dispose();
                return displayName;
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught:\n\n" + e.ToString());
            }
            return null;
        }

最后,当我有我的用户列表时,我可以点击他们的链接,然后使用此功能加载有关用户的信息:

public List<KeyValuePair<string,string>> GetUserInfoBySAMAN(string sAMAccountName)
        {
            try
            {
                DirectoryEntry ldapConnection = createDirectoryEntry();
                DirectorySearcher search = new DirectorySearcher(ldapConnection);


                search.Filter = "(sAMAccountName=" + sAMAccountName + ")";
                search.PropertiesToLoad.Add("objectSID");
                search.PropertiesToLoad.Add("displayName");
                search.PropertiesToLoad.Add("memberOf");
                search.PropertiesToLoad.Add("description");
                search.PropertiesToLoad.Add("accountExpires");
                search.PropertiesToLoad.Add("sAMAccountName");
                result = search.FindOne();

                ///Conversion du SID en chaine de caractères
                var sidInBytes = (byte[])result.Properties["objectSID"][0];
                var sid = new SecurityIdentifier(sidInBytes, 0);

                String time;
                if (result.Properties["accountExpires"][0].ToString().Equals("0")|| result.Properties["accountExpires"][0].ToString().Equals("9223372036854775807"))
                {
                    time = "Jamais";
                }
                else
                {
                    ///Conversion de la date en entier puis en date
                    DateTime dt = new DateTime(1601, 01, 02).AddTicks((Int64)result.Properties["accountExpires"][0]);
                    time = dt.ToString();
                }

                string desc="";
                if (result.Properties.Contains("description"))
                {
                    desc = result.Properties["description"][0].ToString();
                }
                else
                {
                    desc = "Pas de description disponible";
                }
                userInfo = new List<KeyValuePair<string, string>>()
                {
                    new KeyValuePair<string, string>("displayName",result.Properties["displayName"][0].ToString()),
                    new KeyValuePair<string, string>("memberOf", result.Properties["memberOf"][0].ToString()),
                    new KeyValuePair<string, string>("accountExpires",time),
                    new KeyValuePair<string, string>("description",desc),
                    new KeyValuePair<string, string>("sid",sid.ToString()),
                    new KeyValuePair<string, string>("sAMAccountName",result.Properties["sAMAccountName"][0].ToString())
                    /*lastName.Add(result.Properties["displayName"][0].ToString());
                    lastName.Add(result.Properties["memberOf"][0].ToString());
                    lastName.Add(sid.ToString());
                    lastName.Add(result.Properties["accountExpires"][0].ToString());
                    lastName.Add(result.Properties["description"][0].ToString());*/
                };

                return userInfo;
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception caught:\n\n" + e.ToString());
            }
            return null;
        }

如果我用distinguishedName更改sAMAccountName,那么最后一个函数不起作用,因为显然这个属性不能像那样使用。我想使用distinguishedName并立即拥有我的对象。

所以我需要的是在我输入时进行搜索,如果我选择其中一个建议的选项,请立即验证表格,然后将我发送到用户信息页面。

感谢您的帮助,希望它足够清楚

编辑我添加了第二个脚本,可以获取所选项目的值,但我需要通过控制器传递的数据

1 个答案:

答案 0 :(得分:0)

如果我理解正确,autocomplete方法有select事件。

 $(document).ready(function () {
    $("#searchName").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Home/SearchUserWhileTyping",
                type: "GET",
                data: { name: $("#searchName").val() },
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $("#searchName").html(''),
                    response($.map(data, function (item) {
                        return {
                            label: item
                        }
                    }));
                },

               select: function(e, ui)
               {
                 //Just Example
                 $.get("UserController", {ID: ui.Id}).done(
                  function(data){
                  });
                 //Write your ajax post or get method
                 //that fetches user data directly as soon as 
                 //the item in list clicked
               }  
            });
        },
        minLength: 4
    })
});

编辑:我看到了你的编辑,这样你就可以在select事件中使用你的GetUserInfoBySAMAN函数来获取ajax get请求(而不是我写的&#34; UserController&#34;),你有绑定的工作也可以将数据返回到输入或标签。