Question

I have a JSON object with numerous properties that I am submitting to a C# web service via jQuery.ajax() - it looks something like this:

var obj = {};
obj.LanguageCode = 1031;
obj.Gender = { 'Geschlecht': 'Mann' };
obj.City = { 'Stadt': 'Berlin' };
...

Some properties, like Gender and City, store a localized/translated prompt and response that I want to map to a KeyValuePair. I've tried formatting the Javascript in different ways, but the data only comes through when the datatype is Dictionary - when the datatype is KeyValuePair it doesn't work. For example:

private Dictionary Gender { get; set; } // works: Gender[0] == {[Geschlecht,Mann]}
private KeyValuePair City { get; set; } // doesn't work: City == {[,]}

I can use Dictionary if necessary since it works, but it seems like KeyValuePair is more appropriate and cleaner to use. Can you map Javascript objects to KeyValuePairs, or am I stuck with using Dictionary?

Was it helpful?

Solution

Looks like you need a collection of KeyValuePair objects, not a single one (even though your collection would only have one item) - that's all a Dictionary is, a collection with a few helpers around it.

But personally, I'd recommend building an actual class to represent your values, to organize it a little better - a little more verbose, but I think it's worth it.

// C#
public class LocalAndTranslated {
    public string Localized { get;set; }
    public string Translated { get;set; }
}

// JS
obj.Gender = { Localized: "Geschlecht", Translated: "Man" };

If you wanted to, you can even go so far as to define a "class" in javascript:

var LocalAndTranslated = (function() {
    function LocalAndTranslated(localized, translated) {
        this.Localized = localized;
        this.Translated = translated;
    }
    return LocalAndTranslated;
})();

obj.Gender = new LocalAndTranslated("Geschlecht", "Man");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top