【问题标题】:Populate jQuery Autocomplete source from hidden field从隐藏字段填充 jQuery 自动完成源
【发布时间】:2015-10-25 23:58:46
【问题描述】:

首先,我在代码隐藏中生成一个字符串列表。我想将此列表保存到隐藏字段,然后将该列表用作 jquery 自动完成功能的“源”。我应该将我的列表转换为 Json 吗?

我尝试了类似的方法,但没有成功:

var addressJson = JsonConvert.SerializeObject(addresses);


<input type="hidden" name="Addresses" id="Addresses" value="@addressJson"/>

【问题讨论】:

    标签: jquery json autocomplete asp.net-mvc-5


    【解决方案1】:

    看看我的回答

    我的隐藏字段:

    <input type="hidden" runat="server" id="hfExistingTagList" class="tag-list" data-tag="" />
    

    我的 jquery 脚本通过 ajax 从代码隐藏中获取值。小心我在这里使用"when" & "done" 方法,以便在调用自动​​完成方法之前填充隐藏的输入:

    $(document).ready(function () {
            $.when($.ajax({
                type: "POST",
                url: "NewsEditor.aspx/GetAvailableTags",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    if (result.hasOwnProperty("d")) {
                        // The .d is part of the result so reference it
                        //  to get to the actual JSON data of interest
                        $('#hfExistingTagList').data('tag',result.d);
                    }
                    else {
                        // No .d; so just use result
                        $('#hfExistingTagList').data('tag', result.d);
                    }
                }
            })).done((function () {
                $dbTags = $('#hfExistingTagList').data('tag').replace(/'/g, '').split(','); //Build the array used as the source for the autocomplete
                $('#tbMetatags').tagEditor({
                    autocomplete: {
                        delay: 0, //show suggestions immediately
                        position: { collision: 'flip' },
                        source:  $dbTags
                    },
                    //...
                    //Some stuff within my tageditor plugin
                    }
                });
            }))});
    

    最后是 c# 中的 webmethod:

    [WebMethod]
        public static string GetAvailableTags()
        {
            // Put logic here to return list of tags (i.e. load from database)
            var tags = new[] { "ActionScript", "Scheme" };
            return String.Join(",", tags.Select(x => String.Format("'{0}'", x)));
        }
    

    希望这会有所帮助!非常适合我!

    【讨论】:

      猜你喜欢
      • 2011-08-18
      • 1970-01-01
      • 2011-02-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多