2016-01-14 104 views
0

我正在使用ASP.NET MVC創建JSON鍵/值字符串和Javascript來訪問它。我試了幾個例子(見下文),但其中只有一個似乎工作,在那裏我硬編碼元素的id(這顯然不是我想要的)。其他一切都會拋出未定義或異常。爲了澄清,我只是試圖從JSON字符串中獲取值(短語),給定密鑰。從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表明我這個..

enter image description here

但是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']

有可能是一個容易修復那裏,但我沒有找到一個。

+0

所以真的,你有一個奇怪的對象與兩個鍵的數組,一個是'Key'另一個'Phrase',你不能訪問這些對象的價值? – adeneo

回答

0

但是dict ['we-can-deliver-to-po-boxes']返回undefined。

因爲'we-cannot-deliver-to-po-boxes'是一個屬性值,而不是屬性名

這將工作(但不能用,很明顯):

的dict [63] [ '短語']

爲什麼不呢? dict顯然是一個數組,並且每個索引都有一個帶有keyphrase屬性的對象。

,如果您需要在dict陣列搜索特定phrase值,那麼你需要遍歷dict並找到與特定鍵

function findKeyPhrase(someKeyName) 
{ 
    var value = ""; 
    dict.forEach(function(element){ 
     if (element.key == someKeyName) 
     { 
     value = element.phrase; 
     } 
    }); 
    console.log(value); 
    return value; 
} 
console.log(findKeyPhrase ("we-cannot-deliver-to-po-boxes")); 
+0

我會試試這個功能。 Thanks.Using ID不起作用,因爲我的MVC代碼從字典中提取了一個項目列表,可能隨時更改。 63可能會變成64,或其他的東西等等。 – Paul

+0

工作的很好,謝謝 – Paul

1

短語來創建一個正確的字典,使用Dictionary<TKey, TValue>

A List<T>被序列化爲一個數組,即使列表中的項目是「dictionary like」。

當您稍後嘗試從客戶端JavaScript訪問值,您目前使用的括號符號,其通常用於數組:

dict['we-cannot-deliver-to-po-boxes'] 

使用對象爲好,但它的使用點符號和一個有效的鍵名稱更常見:

dict.weCannotFeliverToPoBoxes 
+0

這不適合我。我從服務器端代碼中取出了JSON序列化代碼,並將一些代碼添加到Dictionary 中,並返回該類型(77個條目)。在我的Javascript中,window.ncpDictionary是不確定的.. – Paul

+0

@Paul - 那麼你做錯了什麼。您應該查看生成的HTML並準確查看您獲得的內容。 – Amit