【发布时间】:2016-01-14 18:16:48
【问题描述】:
我正在使用 ASP.NET MVC 创建一个 JSON 键/值字符串和 Javascript 来访问它。我已经尝试了一些示例(见下文),但其中只有一个似乎有效,我在其中硬编码了元素的 id(这显然不是我想要的)。其他一切都抛出未定义或异常。为了澄清,我只是想从 JSON 字符串中获取值(短语),给定键。
我的代码如下。
public string GetNcpJsonDictionary()
{
// Get a list of all dictionary items.
var db = Database.GetDatabase(EnvironmentHelper.IsProduction ? "pub" : "web");
var ncpDictionaryFolder = db.GetItem(ItemIdMapper.Instance.DictionaryNcpItemId);
var ncpDictionaryItems = ncpDictionaryFolder.Axes.GetDescendants().ToList();
var condensedDictionaryItemList = new List<DictionaryItem>();
foreach (var dictionaryItem in ncpDictionaryItems)
{
condensedDictionaryItemList.Add(new DictionaryItem
{
Key = SitecoreApiHelper.GetFieldValue(dictionaryItem.ID.ToString(), "Key"),
Phrase = SitecoreApiHelper.GetFieldValue(dictionaryItem.ID.ToString(), "Phrase")
});
}
var result = JsonConvert.SerializeObject(condensedDictionaryItemList);
return result;
}
在我看来,我说:
<script>
window.ncpDictionary = @Html.Action("GetNcpJsonDictionary", "NCP");
</script>
Javascript:
var dict = window.ncpDictionary;
if (dict != null) {
$("label[for='AccountBaseModel_Person_Address']").append(dict['we-cannot-deliver-to-po-boxes']);
}
JSON 输出如下:
[{"Key":"some-key","Phrase":"some phrase"},...,...]
调试 JS 向我展示了这一点..
但是dict['we-cannot-deliver-to-po-boxes'] 返回未定义。
我也试过了:
dict.we-cannot-deliver-to-po-boxes
dict.getString('we-cannot-deliver-to-po-boxes')
这会起作用(但显然不能使用):
dict[63]['Phrase']
那里可能有一个简单的解决方法,但我还没有找到。
【问题讨论】:
-
所以你真的有一个带有两个键的奇怪对象数组,一个是
Key,另一个是Phrase,你不能按值访问这些对象?
标签: javascript json asp.net-mvc dictionary