jquery 选择文本时自动完成显示 ID

jquery autocomplete shows id when selecting a text

在我的应用程序中,当从自动完成文本框的下拉列表中选择一个值时,它只显示 ID 而不是值 我的代码如下

[AcceptVerbs(HttpVerbs.Post)]
    public JsonResult Autocomplete(string term)
    {
        List<DemoModel> demo = new List<DemoModel>();
        demo.Add(new DemoModel(1, "one"));
        demo.Add(new DemoModel(2, "two"));
        return Json(demo, JsonRequestBehavior.AllowGet);
    }

我的观点

$(document).ready(function () {


    $("#PassId").autocomplete({
        source: function (request, response) {

            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                url: "@(Url.Action("Autocomplete", "Home"))",
                data: { "term": request.term },
                success: function (data) {


                    response($.map(data, function (item) {

                        return { label: item.name, value: item.id };
                    }))
                },
                select: 
        function (event, ui) {

            $("#PassId").val(ui.item.label);
            return false;
        },

                focus: function(event, ui) {

                    $("#PassId").val(ui.item.label);
                    return false;
                }
            });
        }
    });
});

我哪里做错了?谢谢。

我猜在此之前:

}, // <-----before this
select:

您必须关闭 ajax 方法:

  }); //<----this closing of ajax is missing.
},
select:

或者我会说有语法错误,检查一下:

$("#PassId").autocomplete({
  source: function(request, response) {

    $.ajax({
          async: false,
          cache: false,
          type: "POST",
          url: "@(Url.Action(" Autocomplete ", " Home "))",
          data: { "term": request.term },
          success: function(data) {
            response($.map(data, function(item) {
              return {
                label: item.name,
                value: item.id
              };
            }))
          });
      },
      select: function(event, ui) {

        $("#PassId").val(ui.item.label);
        return false;
      },

      focus: function(event, ui) {

        $("#PassId").val(ui.item.label);
        return false;
      } // <---you had a wrong closing here.
  }
});

脚本结构需要一些修复,"select" 和 "focus" 部分位于 "source" 函数中。

应该是这样的:

$('#myAutocomplete').autocomplete({
    source: function (request, response) {
        $.ajax({
            // your ajax parameters
            success: function (data) {
               // your code
            }
        });
    },
    select: function (event, ui) {
       // code on select
    },
    focus: function (event, ui) {
       // code on focus
    }
});