【问题标题】:How to Implement Autocomplete Textbox in MVC如何在 MVC 中实现自动完成文本框
【发布时间】:2017-09-18 00:31:18
【问题描述】:

我在使用硬编码数据自动完成文本框时遇到问题,我的 json“搜索”方法没有触发我一直在搜索很多代码,将其实现到我的项目中,但尚未取得任何成功。我不知道问题出在哪里。请帮助我提前谢谢

型号:

  public class Locations
    {

        public int Id { get; set; }
        public string Name { get; set; }

    }

控制器:

public JsonResult Search(string query)
        {
            List<Locations> locations = new List<Locations>()
        {
            new Locations() {Id = 1, Name = "London"},
            new Locations() {Id = 2, Name = "Walles"},
            new Locations() {Id = 3, Name = "Birmingham"},
            new Locations() {Id = 4, Name = "Edinburgh"},
            new Locations() {Id = 5, Name = "Glasgow"},
            new Locations() {Id = 6, Name = "Liverpool"},
            new Locations() {Id = 7, Name = "Bristol"},
            new Locations() {Id = 8, Name = "Manchester"},
            new Locations() {Id = 9, Name = "NewCastle"},
            new Locations() {Id = 10, Name = "Leeds"},
            new Locations() {Id = 11, Name = "Sheffield"},
            new Locations() {Id = 12, Name = "Nottingham"},
            new Locations() {Id = 13, Name = "Cardif"},
            new Locations() {Id = 14, Name = "Cambridge"},
            new Locations() {Id = 15, Name = "Bradford"},
            new Locations() {Id = 16, Name = "Kingston Upon Hall"},
            new Locations() {Id = 17, Name = "Norwich"},
            new Locations() {Id = 18, Name = "Conventory"}

            };
            List<string> Loc;
            Loc = locations.Where(x => x.Name.StartsWith(query.ToLower())).Select(x => x.Name).ToList();
            return Json(Loc, JsonRequestBehavior.AllowGet);
        }

查看:

@model IEnumerable<SearchBox.Models.Locations>
@using SearchBox.Models
@{
    ViewBag.Title = "Index";
}

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

<script type="text/javascript">
    $("#tags").autocomplete({
        source: '@Url.Action("Search")'
    });
</script>

    <input type="text" id="tags" />

【问题讨论】:

  • 您可能需要在源分配中使用 AJAX 调用:source: function (request, response) { $.ajax({ ... }) }) 并将 URL 参数设置为 url: '@Url.Action("Search")' 这样做,或者在 Url.Action 辅助方法中添加 query 字符串参数。跨度>
  • @TetsuyaYamamoto 试过这个,但我不知道问题出在哪里,什么也没发生 :(
  • 即使是Json方法也不调用list绑定的地方

标签: c# jquery asp.net-mvc jquery-ui


【解决方案1】:

您需要发出 ajax 请求,而不是只在数据源中传递 url。

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

<input type="text" id="tags" />

<script type="text/javascript">
    $("#tags").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("Search")',
                dataType: "jsonp",
                data: {
                    term: request.term
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.Name,
                            value: item.Id
                        };
                    }));
                }
            });
        },
        minLength: 2,
        select: function (event, ui) {

        }
    });
</script>

了解如何使用autocomplete with ajax request

【讨论】:

  • 什么都没发生,我已经尝试过这个解决方案,但问题还是一样
  • @MuhammadAamir :您是否已将jquery 包括在内,因为它在我的最后工作。
  • 是的@Amit Kumar 我已经在我的视图页面顶部包含了 Jquery 就像这样......你在说这个吗??
  • @MuhammadAamir :您还需要包含 jquery 包。 &lt;script src="~/Content/jquery-1.12.4.js"&gt;&lt;/script&gt;
【解决方案2】:

我已经在我的项目中实现了这一点。请检查您是否可以使用它

<div class="tag_cover" style="margin-top:60px; margin-left:57px">
 <input type="text" style="width:300px; display:inline-block; border:transparent" class="tag_input brzero has-icon" id="SkillSet" list="json-datalist" placeholder="Employee name or Skills">
 <datalist id="json-datalist"></datalist>    
</div>

JQuery:

  $(".tag_input").keyup(function (e) {
        var type = $("input[name='search']:checked").val();
        if (type == "Name") {
            var sString = $("#SkillSet").val();
            if (sString == null || sString == "") {
                e.preventDefault();
            }
            else {
                $.ajax({
                    url: "@Url.Action("GetEmployeeNameByKeyword","Home")",
                    type: "POST",
                    data: { 'SearchedString': sString },
                    dataType: "json",
                    success: function (data) {
                        if (data == null || data == "") {
                            //alert("no skills found");
                        }
                        else {
                            var dataList = document.getElementById('json-datalist');
                            $(dataList).empty();
                            $.each(data, function (key, value) {
                                $(dataList).append($('<option>').text(value.UserNames.trim()).attr("value", value.UserId));
                            });
                        }
                    },
                    error: function () {
                        alert("failure");
                    }
                });
            }
        }
    }

控制器:

   public JsonResult GetEmployeeNameByKeyword(string SearchedString)
    {
        List<UserProfile> EmployeeNames = new List<UserProfile>();
        EmployeeNames = _db.UserProfiles.Where(i => i.UserNames.Contains(SearchedString)).ToList();
        return Json(EmployeeNames, JsonRequestBehavior.AllowGet);
    }

【讨论】:

  • 当我开始在文本框中输入时没有任何显示,即使它没有触发 json 方法
  • 你必须调试每一行代码。检查在文本框中输入的字符是否正在调用 jquery 方法。放调试器;在某些时候并验证执行。
  • 它没有调用 Jquery 方法
  • 此代码不起作用。根本无法调用 JS 函数。
【解决方案3】:

我自己一直在到处寻找有关此类功能的参考资料。

我没有足够的代表发表评论,但是在我开始使用 console.log("PASS"); 一次一行之后,Naveen 的回答对我有用。如果从未在诸如 keyup 之类的事件上调用该函数,则可能意味着其中一个变量名称错误或语法错误。您无法调用 javascript 的原因是缺少 });,这是 JQuery 函数的结束语句。脚本部分的代码结尾应如下所示:

           }
        }); //END $.ajax
      }
    }
});         //END keyup function

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    相关资源
    最近更新 更多