使用json数据的jQueryUI + ASP .NET MVC自动完成

时间:2011-07-02 12:39:31

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

使用jQueryUI自动完成功能调用JSON时遇到了很大的问题。 我有这个相当简单的JS:

$(document).ready(function() {
    $('#Editor_Tags').autocomplete({
        source: "/Forums/Ajax/GetTags",
        focus: function () {
            // prevent value inserted on focus
            return false;
        },
        select: function (event, ui) {
            var terms = split(this.value);
            // remove the current input
            terms.pop();
            // add the selected item
            terms.push(ui.TagName);
            // add placeholder to get the comma-and-space at the end
            terms.push("");
            this.value = terms.join(", ");
            return false;
        }
    });
});

这是我想要回归的模特:

public class TagView
{
    public int TagId { get; set; }
    public string TagName { get; set; }
    public int Weight { get; set; }
}

但这不是主要问题。 主要问题是,当我开始输入时,jQuery不向控制器发出请求。我百分百肯定,Url的说法很好。因为我可以通过键入/ Forums / Ajax / GetTags?term = text来手动访问控制器 我得到了结果。 我正在使用新版jQuery和jQUI直接使用谷歌CDN。

2 个答案:

答案 0 :(得分:5)

jQueryUI自动完成小部件需要source参数中的数据满足以下要求:

  

[..]一个简单的字符串数组,或者它   包含每个项目的对象   数组,带有标签或值   财产或两者兼而有之。

所以你有两个选择:

  1. 将您要序列化的视图模型更改为JSON以满足这些要求:

    public class TagView
    {
        public string Label { get; set; }
        public string Value { get; set; }
    }
    
  2. 将自动完成窗口小部件的source参数更改为您自己执行AJAX调用并正确格式化数据的函数:

    $("#Editor_Tags").autocomplete({
        source: function (request, response) {
            $.getJSON("/Forums/Ajax/GetTags", { term: request.term }, function (data) {
                response($.map(data, function (el) {
                    return {
                        label: el.TagName,
                        value: el.TagId
                    };
                }));
            });
        },
        /* other autocomplete options */
    });
    

    这假设从服务器返回的数据是TagView个对象的JSON数组。

  3. 第二段代码未经测试,但至少应该让你朝着正确的方向前进。

答案 1 :(得分:0)

我已经使用了这段代码:

    $('#Editor_Tags').autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "/Forums/Ajax/GetTags",
            dataType: "json",
            data: {
                term: request.term
            },
            success: function (data) {
                response($.map(data, function (item) {
                    return {
                        label: item.TagName,
                        value: item.TagName
                    }
                }));
            }
        });
    }

});

与安德鲁发布的内容没有什么不同。

相关问题