Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象
在上一篇Blog文章中,讲述了JavaScript与Silverlight托管代码相互调用的一些方法。实际上,HtmlWindow的GetProperty方法和Invoke/InvokeSelf方法的返回值是Object类型的,代表 DOM对象或者JavaScript对象(HtmlDocument、HtmlElement、HtmlObject、ScriptObject)的返回值自动作为最接近的类型进行返回,但是,程序开发人员仍然需要明确地将该对象转换成相应的类型。所有的数字,由于跨浏览器的原因,都作为Double类型返回,如果需要Int32类型,则执行Convert.ToInt32()方法即可。
在现代的Web应用中,JSON的使用越来越频繁。Silverlight 2中要调用JavaScript中的JSON对象,首先在托管代码中声明一个类,类的属性与JSON对象的属性一致(不必完全一致),然后在托管代码中将ScriptObject对象转换成声明的这个类型即可。
下面是一个完整的例子:
Page.xaml:
<UserControlx:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="600"Height="480">
<Gridx:Name="LayoutRoot"Background="White">
<CanvasCanvas.Top="20">
<TextBlockCanvas.Top="10"Canvas.Left="20">请输入您的姓名:</TextBlock>
<TextBoxx:Name="UserInput"Width="200"Height="30"Canvas.Top="40"Canvas.Left="20"></TextBox>
<TextBlockx:Name="Msg"Canvas.Top="90"Canvas.Left="20"Foreground="Navy"FontSize="18"Width="500"></TextBlock>
<ButtonClick="Button_Click"Content="单击我"FontSize="24"Width="160"Height="60"x:Name="BtnTest"Canvas.Top="160"Canvas.Left="20"></Button>
<ButtonClick="JSONButton_Click"Content="JavaScriptJSON对象测试"FontSize="24"Width="300"Height="50"Canvas.Top="240"Canvas.Left="20"></Button>
<TextBlockx:Name="Msg2"Canvas.Top="300"Canvas.Left="20"Foreground="Navy"FontSize="18"Width="500"></TextBlock>
<TextBlockx:Name="Msg3"Canvas.Top="320"Canvas.Left="20"Foreground="Navy"FontSize="18"Width="500"></TextBlock>
</Canvas>
</Grid>
</UserControl>
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="600"Height="480">
<Gridx:Name="LayoutRoot"Background="White">
<CanvasCanvas.Top="20">
<TextBlockCanvas.Top="10"Canvas.Left="20">请输入您的姓名:</TextBlock>
<TextBoxx:Name="UserInput"Width="200"Height="30"Canvas.Top="40"Canvas.Left="20"></TextBox>
<TextBlockx:Name="Msg"Canvas.Top="90"Canvas.Left="20"Foreground="Navy"FontSize="18"Width="500"></TextBlock>
<ButtonClick="Button_Click"Content="单击我"FontSize="24"Width="160"Height="60"x:Name="BtnTest"Canvas.Top="160"Canvas.Left="20"></Button>
<ButtonClick="JSONButton_Click"Content="JavaScriptJSON对象测试"FontSize="24"Width="300"Height="50"Canvas.Top="240"Canvas.Left="20"></Button>
<TextBlockx:Name="Msg2"Canvas.Top="300"Canvas.Left="20"Foreground="Navy"FontSize="18"Width="500"></TextBlock>
<TextBlockx:Name="Msg3"Canvas.Top="320"Canvas.Left="20"Foreground="Navy"FontSize="18"Width="500"></TextBlock>
</Canvas>
</Grid>
</UserControl>
Page.xaml.cs:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Animation;
usingSystem.Windows.Shapes;
usingSystem.Windows.Browser;
usingSystem.Runtime.Serialization.Json;
namespaceSilverlightApplication1
{
publicpartialclassPage:UserControl
{
publicPage()
{
InitializeComponent();
}
privatevoidButton_Click(objectsender,RoutedEventArgse)
{
stringUserInputContent=this.UserInput.Text;
if(UserInputContent.Equals(String.Empty))
{
UserInputContent="HelloSilverlightWorld!";
}
else
{
UserInputContent="你好,"+UserInputContent;
}
HtmlWindowwin=HtmlPage.Window;
this.Msg.Text=UserInputContent;
win.Alert("Silverlight里面弹出的对话框。 "+UserInputContent);
//执行页面中的js函数:
win.Eval("getArrayTest()");
Object[]args={"将此参数传递给js函数"};
win.Invoke("getArrayTest",args);
//如果页面中的值
HtmlDocumentdoc=HtmlPage.Document;
doc.GetElementById("UserName").SetAttribute("value",this.UserInput.Text);
}
[ScriptableMember()]
publicstringInterInvole()
{
stringusername=HtmlPage.Document.GetElementById("UserName").GetAttribute("value");
this.UserInput.Text=username;
this.Msg.Text="您输入了:"+username;
return"你从js脚本中调用了Silverlight里面的方法。";
}
privatevoidJSONButton_Click(objectsender,RoutedEventArgse)
{
ScriptObjectso=HtmlPage.Window.Invoke("ReturnObject",null)asScriptObject;
Staples=so.ConvertTo<Staple>();
this.Msg2.Text="大家好,我在JavaScriptJSON对象中的名称是:"+s.UserName;
}
//接受Html页面传递的JSON字符串
[ScriptableMember()]
publicvoidReveiveJSON(stringjsonString)
{
//注意引用:System.Runtime.Serialization.Json
DataContractJsonSerializerjson=newDataContractJsonSerializer(typeof(Staple));
System.IO.MemoryStreamms=newSystem.IO.MemoryStream(System.Text.Encoding.Unicode.GetBytes(jsonString));
Staplestaple=newStaple();
staple=(Staple)json.ReadObject(ms);
Msg3.Text="UserId="+staple.UserId.ToString()+",UserName="+staple.UserName;
}
}
publicclassStaple
{
publicstringUserName{set;get;}
publicDoubleUserId{set;get;}
}
}
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Animation;
usingSystem.Windows.Shapes;
usingSystem.Windows.Browser;
usingSystem.Runtime.Serialization.Json;
namespaceSilverlightApplication1
{
publicpartialclassPage:UserControl
{
publicPage()
{
InitializeComponent();
}
privatevoidButton_Click(objectsender,RoutedEventArgse)
{
stringUserInputContent=this.UserInput.Text;
if(UserInputContent.Equals(String.Empty))
{
UserInputContent="HelloSilverlightWorld!";
}
else
{
UserInputContent="你好,"+UserInputContent;
}
HtmlWindowwin=HtmlPage.Window;
this.Msg.Text=UserInputContent;
win.Alert("Silverlight里面弹出的对话框。 "+UserInputContent);
//执行页面中的js函数:
win.Eval("getArrayTest()");
Object[]args={"将此参数传递给js函数"};
win.Invoke("getArrayTest",args);
//如果页面中的值
HtmlDocumentdoc=HtmlPage.Document;
doc.GetElementById("UserName").SetAttribute("value",this.UserInput.Text);
}
[ScriptableMember()]
publicstringInterInvole()
{
stringusername=HtmlPage.Document.GetElementById("UserName").GetAttribute("value");
this.UserInput.Text=username;
this.Msg.Text="您输入了:"+username;
return"你从js脚本中调用了Silverlight里面的方法。";
}
privatevoidJSONButton_Click(objectsender,RoutedEventArgse)
{
ScriptObjectso=HtmlPage.Window.Invoke("ReturnObject",null)asScriptObject;
Staples=so.ConvertTo<Staple>();
this.Msg2.Text="大家好,我在JavaScriptJSON对象中的名称是:"+s.UserName;
}
//接受Html页面传递的JSON字符串
[ScriptableMember()]
publicvoidReveiveJSON(stringjsonString)
{
//注意引用:System.Runtime.Serialization.Json
DataContractJsonSerializerjson=newDataContractJsonSerializer(typeof(Staple));
System.IO.MemoryStreamms=newSystem.IO.MemoryStream(System.Text.Encoding.Unicode.GetBytes(jsonString));
Staplestaple=newStaple();
staple=(Staple)json.ReadObject(ms);
Msg3.Text="UserId="+staple.UserId.ToString()+",UserName="+staple.UserName;
}
}
publicclassStaple
{
publicstringUserName{set;get;}
publicDoubleUserId{set;get;}
}
}
App.xaml.cs:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Animation;
usingSystem.Windows.Shapes;
usingSystem.Windows.Browser;
namespaceSilverlightApplication1
{
publicpartialclassApp:Application
{
publicApp()
{
this.Startup+=this.Application_Startup;
this.Exit+=this.Application_Exit;
this.UnhandledException+=this.Application_UnhandledException;
InitializeComponent();
}
privatevoidApplication_Startup(objectsender,StartupEventArgse)
{
//Loadthemaincontrol
Pagep=newPage();
HtmlPage.RegisterScriptableObject("SilverlightApplicationExample",p);
//请注意这里的定义方法,如果这里的p写成newPage(),则Javascript基本不能给UserInput赋值!
this.RootVisual=p;
}
privatevoidApplication_Exit(objectsender,EventArgse)
{
}
privatevoidApplication_UnhandledException(objectsender,ApplicationUnhandledExceptionEventArgse)
{
}
}
}
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Animation;
usingSystem.Windows.Shapes;
usingSystem.Windows.Browser;
namespaceSilverlightApplication1
{
publicpartialclassApp:Application
{
publicApp()
{
this.Startup+=this.Application_Startup;
this.Exit+=this.Application_Exit;
this.UnhandledException+=this.Application_UnhandledException;
InitializeComponent();
}
privatevoidApplication_Startup(objectsender,StartupEventArgse)
{
//Loadthemaincontrol
Pagep=newPage();
HtmlPage.RegisterScriptableObject("SilverlightApplicationExample",p);
//请注意这里的定义方法,如果这里的p写成newPage(),则Javascript基本不能给UserInput赋值!
this.RootVisual=p;
}
privatevoidApplication_Exit(objectsender,EventArgse)
{
}
privatevoidApplication_UnhandledException(objectsender,ApplicationUnhandledExceptionEventArgse)
{
}
}
}
SilverlightApplication1TestPage.aspx:
<%@PageLanguage="C#"AutoEventWireup="true"%>
<%@RegisterAssembly="System.Web.Silverlight"Namespace="System.Web.UI.SilverlightControls"TagPrefix="asp"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>Silverlight2托管代码与Javascript交互的例子</title>
<scripttype="text/javascript">
//<!{CDATA[
//定义全局变量:
vartestVar="孟宪会";
//定义全局函数:
functiongetArrayTest()
{
if(arguments.length>0)
{
alert("js对话框:您传递了参数。"+arguments[0]);
returnarguments[0];
}
else
{
alert("js对话框:无参数调用。");
return"js函数返回值";
}
}
functionSetUserName()
{
alert(SilverlightPlugin.Content.SilverlightApplicationExample.InterInvole());
}
varStaple={
UserId:100,
UserName:'孟宪会',
SayHello:function(){alert(this.UserName)}
};
functionReturnObject()
{
returnStaple;
}
functionSendJSONToSilverlight()
{
SilverlightPlugin.Content.SilverlightApplicationExample.ReveiveJSON(JSON.stringify(Staple));
}
//定义Silverlight插件对象
varSilverlightPlugin=null;;
functionpluginLoaded(sender)
{
SilverlightPlugin=sender.get_element();
}
//]]>
</script>
<scriptsrc="json2.js"type="text/javascript"></script>
<!--http://www.JSON.org/json2.js-->
</head>
<bodystyle="height:100%;margin:0;">
<formid="form1"runat="server">
<divstyle="border:2pxsolid#EEE;margin:20px;padding:20px">
请输入你的名字:<inputid="UserName"type="text"value=""/>
<inputtype="button"onclick="SetUserName()"value="将名字传递到Silverlight"/><inputtype="button"onclick="SendJSONToSilverlight()"value="将JSON传递到Silverlight"/>
</div>
<br/>
<divstyle="border:2pxsolid#EEE;margin:20px;">
<asp:ScriptManagerID="ScriptManager1"runat="server">
</asp:ScriptManager>
<asp:SilverlightID="Xaml1"runat="server"OnPluginLoaded="pluginLoaded"Source="~/ClientBin/SilverlightApplication1.xap"Version="2.0"Width="600px"Height="480px"/>
</div>
</form>
</body>
</html>
<%@RegisterAssembly="System.Web.Silverlight"Namespace="System.Web.UI.SilverlightControls"TagPrefix="asp"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>Silverlight2托管代码与Javascript交互的例子</title>
<scripttype="text/javascript">
//<!{CDATA[
//定义全局变量:
vartestVar="孟宪会";
//定义全局函数:
functiongetArrayTest()
{
if(arguments.length>0)
{
alert("js对话框:您传递了参数。"+arguments[0]);
returnarguments[0];
}
else
{
alert("js对话框:无参数调用。");
return"js函数返回值";
}
}
functionSetUserName()
{
alert(SilverlightPlugin.Content.SilverlightApplicationExample.InterInvole());
}
varStaple={
UserId:100,
UserName:'孟宪会',
SayHello:function(){alert(this.UserName)}
};
functionReturnObject()
{
returnStaple;
}
functionSendJSONToSilverlight()
{
SilverlightPlugin.Content.SilverlightApplicationExample.ReveiveJSON(JSON.stringify(Staple));
}
//定义Silverlight插件对象
varSilverlightPlugin=null;;
functionpluginLoaded(sender)
{
SilverlightPlugin=sender.get_element();
}
//]]>
</script>
<scriptsrc="json2.js"type="text/javascript"></script>
<!--http://www.JSON.org/json2.js-->
</head>
<bodystyle="height:100%;margin:0;">
<formid="form1"runat="server">
<divstyle="border:2pxsolid#EEE;margin:20px;padding:20px">
请输入你的名字:<inputid="UserName"type="text"value=""/>
<inputtype="button"onclick="SetUserName()"value="将名字传递到Silverlight"/><inputtype="button"onclick="SendJSONToSilverlight()"value="将JSON传递到Silverlight"/>
</div>
<br/>
<divstyle="border:2pxsolid#EEE;margin:20px;">
<asp:ScriptManagerID="ScriptManager1"runat="server">
</asp:ScriptManager>
<asp:SilverlightID="Xaml1"runat="server"OnPluginLoaded="pluginLoaded"Source="~/ClientBin/SilverlightApplication1.xap"Version="2.0"Width="600px"Height="480px"/>
</div>
</form>
</body>
</html>
单击“JavaScript JSON 对象测试”按钮,运行结果如下: