【问题标题】:Issue with autocomplete textbox using jquery in asp.net mvc在 asp.net mvc 中使用 jquery 的自动完成文本框问题
【发布时间】:2011-11-24 09:09:20
【问题描述】:

我需要创建一个自动完成文本框来填充 ASP.Net MVC 应用程序中的客户姓名。我认为的jQuery代码如下:

$(document).ready(function() {
    $("input#bldCustomerName").autocomplete({
        source: '<%= Url.Action("ListCustomers","Build") %>'
    });
});

我的控制器动作是:

public ActionResult ListCustomers(string term)
    {
        IList<HSTrader> lstTraders = new List<HSTrader>();
        Build objBld = new Build();
        string trdrType = Resources.Resource.TraderTypeCustomer;
        int trdrTypeId = objBld.GetTraderTypeByTraderTypeName(trdrType).Id;
        lstTraders = objBld.GetTradersByTraderType(trdrTypeId);

        var results = from m in lstTraders
                      where m.TraderName.StartsWith(term)
                      select m.TraderName; //new { label = m.TraderName, id = m.Id };

        return Json(results.ToArray(), JsonRequestBehavior.AllowGet);
    }

keypress 上,控制器动作被执行,但列表不会出现在文本框下方。我的实现有什么问题?

【问题讨论】:

  • 您是否在控制台/萤火虫中遇到任何错误?
  • 哦,抱歉,这是区分大小写的情况。它给出了正确的结果。
  • 您可能需要考虑自动完成帮助表单awesome.codeplex.com

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


【解决方案1】:
 $(document).ready(function () {
            $('input#bldCustomerName').autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Build/ListCustomers', type: 'Get', dataType: 'json',
                        data: { term: request.term, maxResults: 10 },
                        success: function (data) {
                            response($.map(data, function (item) {
                                return { label: item.TraderName, value: item.TraderName, id: item.TraderName }

                                //return { label: item.d, value: item.d, id: item.d } 
                                //If it does not work then use this line. comment above line. it is for single dimension array (only one column.).
                            }))
                        }
                    });
                },
                select: function (event, ui) {

                }
            });
        });






        //BuildController
        [HttpGet]
        public JsonResult ListCustomers(string term, int maxResults)
        {
            IList<HSTrader> lstTraders = new List<HSTrader>();
            Build objBld = new Build();
            string trdrType = Resources.Resource.TraderTypeCustomer;
            int trdrTypeId = objBld.GetTraderTypeByTraderTypeName(trdrType).Id;
            lstTraders = objBld.GetTradersByTraderType(trdrTypeId);

            var results = from m in lstTraders
                          where m.TraderName.StartsWith(term)
                          select m.TraderName; //new { label = m.TraderName, id = m.Id };

            return Json(results.Take(maxResults).ToList(), JsonRequestBehavior.AllowGet);
        }

【讨论】:

    【解决方案2】:

    希望这对某人有所帮助...

    我不得不添加 jquery-ui 库和样式表,因为它们没有附带 VS2013 脚本模板。这是一个使用数据库查询和 TextBoxFor 的自动完成示例,对我有用:

    WordListController.cs:

    public ActionResult Test2(MyModel vm)
    {
        return View(vm);
    }
    public JsonResult AutoComplete(string search)
    {
        var result = (from r in db.Words
                      where r.Word.ToLower().StartsWith(search.ToLower())
                      select r.Word).Take(10).ToArray();
    
        return Json(result, JsonRequestBehavior.AllowGet);
    }
    

    Test2.cshtml:

    @{
        ViewBag.Title = "test2";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/jqueryuicss")
    
    @model  WLWeb.Models.MyModel
    
    <h2>test2</h2>
    
    <script>
    
            $(function () {
                $('#tags').autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            url: '@Url.Action("AutoComplete", "WordList")',
                            dataType: "json",
                            contentType: 'application/json, charset=utf-8',
                            data: {
                                search: $("#tags").val()
                            },
                            success: function (data) {
    
                                response($.map(data, function (item) {
                                    return {
                                        label: item
                                    };
                                }));
                            },
                            error: function (xhr, status, error) {
                                alert(error);
                            }
                        });
                    },
                    minLength: 2
                });
            });
    
    </script>
    
        @Html.TextBoxFor(x => Model.SelectionModel.SearchString, new { @id = "tags", style = "width:120px;" })
    

    Layout.csthml:

    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - My ASP.NET Application</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/jqueryval")
    
    </head> 
    <body>
    ...
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
    

    BundleConfig.cs:

    ...
            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.custom.js"));
    
            bundles.Add(new StyleBundle("~/Content/jqueryuicss").Include(
                      "~/Content/jquery-ui-{version}.custom.css"));   
    

    【讨论】:

      猜你喜欢
      • 2020-05-07
      • 2018-02-14
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      相关资源
      最近更新 更多