【问题标题】:Select event on JQuery UI autocompleter is not fired未触发 JQuery UI 自动完成器上的选择事件
【发布时间】:2011-05-13 10:56:45
【问题描述】:

我正在尝试使用 jQuery UI,但我似乎无法弄清楚如何让选择事件执行。

我将自动完成器绑定如下:

$().ready(function () {
    $("#txtPersonSearch").autocomplete({
        source: '<%=Url.Action("GetPeople") %>',
        minLength: 3,
        select: function (event, ui) {
            // This code is never reached
            console.log(ui);
        }
    });
});

我是否缺少可以绑定到选择事件的东西?

【问题讨论】:

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


    【解决方案1】:

    也许您的控制器操作会引发异常。让我们采取以下行动:

    public ActionResult GetPeople(string term)
    {
        // the term parameter will contain the search string
        // TODO: use the term parameter to filter the results from 
        // your repository. In this example the result is hardcoded
        // to verify that the everything works.
        return Json(new[]
        {
            new { id = "1", label = "label 1", value = "value 1" },
            new { id = "2", label = "label 2", value = "value 2" },
            new { id = "3", label = "label 3", value = "value 3" },
        }, JsonRequestBehavior.AllowGet);
    }
    

    注意事项:

    • 可以使用 GET 动词 (JsonRequestBehavior.AllowGet) 访问控制器操作
    • 控制器操作返回一个 JSON 数组,其中每个项目都有一个 id、label 和 value 属性
    • 控制器操作不会引发异常

    然后:

    $(function () {
        $('#txtMovieSearch').autocomplete({
            source: '<%= Url.Action("GetPeople") %>',
            minLength: 3,
            select: function (evt, ui) {
                console.log(ui);
            }
        });
    });
    

    最后使用FireBug 来分析究竟是什么作为AJAX 请求发送到您的服务器以及来自服务器的响应。

    【讨论】:

    • 你是对的!它使用更简单的 JSON 返回。我的控制器返回 Dictionary 将其序列化为 JSON 是否有问题?
    • 看我的例子。序列化字典不会有问题,但插件理解响应会有问题。它需要按照我的示例进行格式化。所以在你的字典上使用简单的.Select() 扩展方法可以让你达到想要的结果:return Json(dico.Select(x =&gt; new { id = x.Key, label = x.Value, value = x.Value }), JsonRequestBehavior.AllowGet);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    相关资源
    最近更新 更多