1

In my view model I have a dictionary that I want to evaluate in a jQuery function. I'm having a tough time mapping between the two languages.

View Model

public Dictionary<int, string> Collection { get; set; }

Script

$("#someButton").click(function () {
    var collection = {};
    var count = '@(Model.Collection.Count)' * 1;
    for (var i = 0; i < count; i++) {
        collection[i] = // Model.Collection[i]
    }
    ...
});

How do I either retrieve values by index directly from my view model's Collection property, or fill a local javascript array with that data so that I can operate on the copy in my function?

I've read a little about Knockout and Json.NET but I'm really hoping to avoid yet another dependency/learning curve in my project.

1 Answer 1

2

JSON only support string as the key. So you could convert the Dictionary<int, string> to Dictionary<string, string> then put it in JS code by serializing it with JSON.NET. For example:

var collection = <%= Model.CollectionJson %>

which in the model:

public string CollectionJson {
    get {
        // correct API as @Superstringcheese suggested
        return JsonConvert.SerializeObject(
            Collection.ToDictionary(p => p.Key.ToString(), p => p.Value));
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I believe a method is a better choice over a property because in general a property implies a low cost calculation.
This was not working for me, but it led me to the realization that Json.NET is far more native than I thought. I ended up with: JsonConvert.SerializeObject(Collection, Formatting.Indented);
@Superstringcheese Thanks, I've corrected the API in the answer.

Your Answer

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