首先,我在代码隐藏中生成一个字符串列表。我想将此列表保存到隐藏字段,然后使用列表作为"源"用于jquery自动完成功能。我应该将我的名单转换为Json吗?
我试过这样的事情,但没有成功:
var addressJson = JsonConvert.SerializeObject(addresses);
<input type="hidden" name="Addresses" id="Addresses" value="@addressJson"/>
答案 0 :(得分: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#中的web方法:
[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)));
}
希望这会有所帮助!对我来说很完美!