简体   繁体   English

Html.TextBox上的自动完成功能不起作用

[英]Autocomplete on Html.TextBox won't work

So, I've searched alot and went through alot of tutorials and even though I do everything exactly as in the tutorial, I just can't seem to get it working. 因此,我已经搜索了很多,并阅读了许多教程,即使我所做的一切都与教程完全相同,但似乎无法使它正常工作。 Funny thing is, I have been involved in a project where we used the exact same solution and it worked. 有趣的是,我参与了一个项目,在该项目中,我们使用了完全相同的解决方案,并且它确实起作用。

I've got a textbox in my forum where users can search for threads in all categories where I am using ajax to show the result in a div in form of a partial view. 我的论坛中有一个文本框,用户可以在其中使用ajax在div中以部分视图的形式显示结果的所有类别中的线程。 This is working. 可以了

The problem is that I want the thread subjects that are containing the current search term to show up (in form of a normal string) while the user is typing, but I can't seem to get the implementation of autocomplete right. 问题是我希望在用户键入时显示包含当前搜索词的线程主题(以普通字符串的形式),但是我似乎无法正确实现自动完成功能。 By the way I am retrieving my information from a MSSQL-database. 顺便说一下,我正在从MSSQL数据库中检索信息。

This is the javascript that I am using to autocomplete (which is not working) and below that you can see my Ajax-form that I use for the search (that works): 这是我用来自动完成(不起作用)的javascript,在下面可以看到我用于搜索(有效)的Ajax表单:

<link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui.min.js"></script>

@*Scripts for  Ajax to show the partial view in the div with id "partialThreads" at request*@
<script src="~/Scripts/jquery-2.2.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>



<script type="text/javascript">
    $(function () {

        $("#txtSearch").autocomplete({
            source: '@Url.Action("GetThreadsBySearch", "Forum")'
        });
    });

</script>


@using (@Ajax.BeginForm("Threads", new AjaxOptions() { UpdateTargetId = "partialThreads", InsertionMode = InsertionMode.Replace, HttpMethod = "POST" }))
{
    @Html.AntiForgeryToken()
    <p><strong>Search for thread in all categories</strong></p>
    @Html.TextBox("searchTerm", null, new { id = "txtSearch", style = "width: 1000px" })
    <input type="submit" value="Search" />
}

Here is the div where I show the results of the search in form of a partial view: 这是div,其中我以部分视图的形式显示搜索结果:

<div id="partialThreads">

</div>

Here is the action method that I am using for my ajax-form search (the working one): 这是我用于ajax形式搜索(有效方法)的操作方法:

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult Threads(string searchTerm)
    {
        var model = string.IsNullOrWhiteSpace(searchTerm)
            ? new List<ThreadsListModel>()
            : _threadRepo.GetThreadsBySearch(searchTerm).OrderByDescending(x => x.DateCreated).ToList();

        return PartialView("_Threads", model);
    }

And here is the method that I use to retrieve the information to my autocomplete (I've tried setting a break point on it, it doesn't even break): 这是我用来将信息检索到自动完成功能的方法(我尝试在其上设置一个断点,它甚至没有中断):

    public JsonResult GetThreadsBySearch(string term)
    {
        var threadNames = _threadRepo.GetThreadsBySearch(term).Select(x => x.Subject).ToList();
        return Json(threadNames, JsonRequestBehavior.AllowGet);
    } 

Note that I use the same db-query to search with the form and for the autocomplete (only difference would be that I select the threadnames as a List in the GetThreadsBySearch method. So that can't be the problem (?). Here is query-method in case you want to have a look: 请注意,我使用相同的数据库查询来搜索表单和自动完成功能(唯一的区别是,我在GetThreadsBySearch方法中选择了线程名称作为列表。所以这不是问题(?)。查询方法,以防万一:

    public ICollection<ThreadsListModel> GetThreadsBySearch(string subject)
    {
        using (var context = new ForumContext())
        {
            return
                context.Threads.Where(x => x.Subject.ToLower().Contains(subject.ToLower()) && x.IsActive)
                    .Select(x => new ThreadsListModel()
                    {
                        ID = x.ID,
                        DateCreated = x.DateCreated,
                        CreatedBy = x.CreatedBy,
                        Subject = x.Subject,
                        PostsCount = x.Posts.Count
                    }).Distinct().ToList();
        }
    }

Also, I am using Visual Studio 2015 (.NET 4.5.2) MVC 5. I hope that I haven't forgot to write down any helpful information. 另外,我正在使用Visual Studio 2015(.NET 4.5.2)MVC5。希望我不会忘记写下任何有用的信息。

您的脚本顺序错误, jquery必须在jquery-ui之前(并确保您没有任何重复的脚本)

 $("#MainContent_txtCountry").autocomplete({
    source: function (request, response) {
        var param = { keyword: $('#MainContent_txtCountry').val() };
        $.ajax({
            url: "Default.aspx/GetCountryNames",
            data: JSON.stringify(param),
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                response($.map(data.d, function (item) {
                    return {
                        value: item
                    }
                }))
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    },

   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM