2

I am accessing a Javascript object (which has a form similar to this: { 1 : "Option 1", 2 : "Option 2", 3 : "Option 3" }) from Silverlight using code similar to the following:

dynamic window = HtmlPage.Window;
var options = window.GlobalObject.getDropdownItems();

Now, the problem is that options is now of type ScriptObject. This wouldn't be a problem if I knew what the names of the properties of my Javascript object were (I could just do options.GetProperty(1) to get the label for the first option). However, this won't work because I need both the values and the names of the options. Is there some way to convert it to a Dictionary<int, string> or something similar?

2 Answers 2

2

Are you able to change the input of the options? If you are, this is what I would suggest.

Change the input of the values to something along these lines:

function getDropdownItems() {
    var items = [{ Value: 1, Name: "Option 1" }, { Value: 2, Name: "Option 2" }, { Value: 3, Name: "Option 3"}];
    return items;
}

Then in Silverlight you can easily convert it to a typed object.

public class Option
{
    public int Value { get; set; }
    public string Name { get; set; }
}

private void LoadOptions()
{
    dynamic window = HtmlPage.Window;
    var dynamicoptions = window.getDropdownItems();

    ScriptObject scriptObject = dynamicoptions as ScriptObject;

    if (scriptObject != null)
    {
        var options = scriptObject.ConvertTo<Option[]>();
        if (options != null)
        {
        }
    }
}

I've found this is the easiest way to work with javascript objects.

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

Comments

1

This is how I solved the problem. First of all, I added a Javascript function called getKeysOfObject, which looks like this:

var getKeysOfObject = function (o)
{
    var keys = [], i;
    for (i in o) {
        keys.push(i);
    }
    return keys;
}

Then I used that function to determine what the keys of my object were. From there, it wasn't too difficult to get the information I needed from the object.

dynamic window = HtmlPage.Window;
dynamic options = window.getDropDownItems();
dynamic keys = window.getKeysOfObject(options);
int numKeys = Convert.ToInt32((double)keys.length);

for (int i = 0; i < numKeys; ++i)
{
    if (options[keys[i]].GetType() == typeof(ScriptObject))
    {
        optionDictionary.Add(new KeyValuePair<int, string>(
            Convert.ToInt32((string)keys[i]),
            (string)options[keys[i]]);
    }
}

The reason for checking the type of the actual property of the object is that silverlight was adding a weird $__slid property to the object.

Comments

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.