0

I'm using ASP.NET MVC to create a JSON key/value string and Javascript to access it. I've tried a few examples (see below) but only one of them seem to work, where I hardcode the id of the element in (which is obviously not what I want). Everything else throws undefined or an exception. To clarify, I'm just trying to get the value (phrase) from the JSON string, given the key.

My code is as follows.

    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;
    }

In my view, I put:

<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']);
}

The JSON outputs like this: [{"Key":"some-key","Phrase":"some phrase"},...,...]

Debugging the JS shows me this..

enter image description here

But dict['we-cannot-deliver-to-po-boxes'] returns undefined.

I've also tried:

dict.we-cannot-deliver-to-po-boxes

dict.getString('we-cannot-deliver-to-po-boxes')

This will work (but can't be used, obviously):

dict[63]['Phrase']

There is probably an easy fix out there, but I haven't found one.

1
  • So really you have an array of strange objects with two keys,one being Key the other being Phrase, and you can't access those objects by value ? Commented Jan 14, 2016 at 18:18

2 Answers 2

1

To create a proper dictionary, use Dictionary<TKey, TValue>.

A List<T> is serialized as an array, even if the items of the list are "dictionary like".

When you later try to access the values from the client side JavaScript, you currently use the bracket notation which is typically used for arrays:

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

This will work with objects as well, but it's more common to use the dot notation with a valid key name:

dict.weCannotFeliverToPoBoxes
Sign up to request clarification or add additional context in comments.

2 Comments

This isn't working for me. I swapped out my JSON serialize code from the server-side code and put in some code that adds the key and value to the Dictionary<string,string> and I return that type (77 entries). In my Javascript, window.ncpDictionary is undefined..
@Paul - then you're doing something wrong. You should view the generated HTML and see exactly what you get.
0

But dict['we-cannot-deliver-to-po-boxes'] returns undefined.

because 'we-cannot-deliver-to-po-boxes' is a property value, not property name

This will work (but can't be used, obviously):

dict[63]['Phrase']

why not? dict is obviously an array and each index has an object with key and phrase property.

if you need to search for a specific phrase value in dict array then you need to iterate dict and find a phrase with a specific key

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" ) );

1 Comment

I'll try this function. Thanks.Using an ID wouldn't work, since my MVC code pulls a list of items from a dictionary that may change at any time. 63 might then become 64, or something else, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.