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

Łuk*_*ran 1 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;
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

这是我试图返回的模型:

public class TagView
{
    public int TagId { get; set; }
    public string TagName { get; set; }
    public int Weight { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

And*_*ker 5

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

[..]一个简单的字符串数组,或者它包含数组中每个项目的对象,带有标签或值属性或两者.

所以你有两个选择:

  1. 将要序列化的viewmodel更改为JSON以满足这些要求:

    public class TagView
    {
        public string Label { get; set; }
        public string Value { get; set; }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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 */
    });
    
    Run Code Online (Sandbox Code Playgroud)

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

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