Http://www.cnblogs.com/sosowjb/archive/2012/06/02/2532237.html
Recently, a Silverlight application needs to use Silverlight to call the JavaScript method on the page. This js method returns an array of objects to Silverlight. How to deal with this object array in Silverlight has been entangled for a while. Through searching, we found a method in the Microsoft developer community.
The js method used for testing is as follows:
1: function test() {
2: var testObjectCollection = [];
3: for (var i = 0; i < 10; i++) {
4: var testObject = new Object();
5: testObject.Field1 = "Field1_" + i;
6: testObject.Field2 = "Field2_" + i;
7: testObjectCollection[testObjectCollection.length] = testObject;
8: }
9: return testObjectCollection;
10: };
The code designs an object testobject, which contains two attributes: field1 and field2. Therefore, it is easy to think of creating a class with the same structure in Silverlight:
1: public class TestObject
2: {
3: public string Field1 { get; set; }
4: public string Field2 { get; set; }
5: }
The preparation ends here.
The code for calling the js method in Silverlight is as follows:
1: object returnedValue = HtmlPage.Window.Invoke("test", null);
The first parameter is the js method name, and the second parameter is of the Params object [] type, which is a list of parameters of the js method. The Return Value of the invoke method is of the object type. It is easy to use the following method for conversion:
1: List<TestObject> testObjectCollection = returnedValue as List<TestObject>;
However, the testobjectcollection variable is null, And the returnedvalue variable is not null. The conversion fails.
Debugging shows that the returnedvalue type is system. Windows. browser. scriptobject. That is to say, the return value of the invoke method is not simply an object, but scriptobject. The scriptobject class has a convertor method that can be used for conversion. For details about the system. Windows. browser. scriptobject type, go to msdn.
So I tried the following method:
1: ScriptObject returnedValue = HtmlPage.Window.Invoke("test", null) as ScriptObject;
2: List<TestObject> objects = returnedValue.ConvertTo<List<TestObject>>();
The debugging result is as follows:
Obviously, the conversion is successful. The rest is handled according to business needs.