SilverLight学习笔记--Silverlight中WebService通讯本文我们学习如何在Silverlight中使用WebService进行通
SilverLight学习笔记--Silverlight中WebService通讯
本文我们学习如何在Silverlight中使用WebService进行通讯。
新建项目Silverlight应用程序,命名为:SLWebService。
在服务器端我们需要做两项目工作:
1、在Web项目中新建一个类Person,我们将在WebService中返回它的实例化对象。Person类定义如下:
?
Code
<!-- <br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->using?System;
using?System.Collections.Generic;
using?System.Linq;
using?System.Web;
using?System.Web.Services;
namespace?SLWebService.Web
{
????///?<summary>
????///?MySLWebService?的摘要说明
????///?</summary>
????[WebService(Namespace?=?"http://tempuri.org/")]
????[WebServiceBinding(ConformsTo?=?WsiProfiles.BasicProfile1_1)]
????[System.ComponentModel.ToolboxItem(false)]
????//?若要允许使用?ASP.NET?AJAX?从脚本中调用此?Web?服务,请取消对下行的注释。
????//?[System.Web.Script.Services.ScriptService]
????public?class?MySLWebService?:?System.Web.Services.WebService
????{
????????[WebMethod]
????????public?string?HelloWorld()
????????{
????????????return?"Hello?World";
????????}
????????[WebMethod]
????????public?Person[]?GetPeople()
????????{
????????????List<Person>?People?=?new?List<Person>()
????????{
???????????new?Person{?Name="Jack",Age=12},
???????????new?Person{?Name="Tom",Age=22},
???????????new?Person{?Name="Simon",Age=32},
???????????new?Person{?Name="Richard",Age=26}
????????};
????????????return?People.ToArray();
????????}
????????
????}
}
在客户端我们需要做如下工作:
1、建立用户界面.Page.xaml代码如下:
?
"?Click="btnGetWebService_Click"></Button>
????????<ListBox?x:Name="People"?Width="300"?Height="200"?Margin="20">
????????????<ListBox.ItemTemplate>
????????????????<DataTemplate>
????????????????????<StackPanel?Orientation="Vertical">
????????????????????????<StackPanel?Orientation="Horizontal">
??????????????????????????<TextBlock?Text="姓名"?Width="100"?Foreground="Blue"?></TextBlock>
??????????????????????????<TextBlock?Text="年龄"?Width="100"?Foreground="DarkBlue"></TextBlock>
????????????????????????</StackPanel>
????????????????????????<StackPanel?Orientation="Horizontal">
????????????????????????<TextBlock?Text="{Binding?Name}"?Foreground="Red"??Width="100"?></TextBlock>
????????????????????????<TextBlock?Text="{Binding?Age}"??Foreground="Green"??Width="100"?></TextBlock>
????????????????????????</StackPanel>
????????????????????</StackPanel>
????????????????</DataTemplate>
????????????</ListBox.ItemTemplate>
????????</ListBox>
????</StackPanel>
</UserControl>
界面如下:
????????????????????????
2、在Silverlight项目中引用服务器端的WebService,命名为MyWebServiceRef。
????????????????????????
引用后,程序如下图:
????????????????????????
3、在客户端使用WebService,通过WebService从服务器端取得数据,在本地处理后显示在用房界面上。Page.xaml.cs代码如下:
?
前往:Silverlight学习笔记清单本文程序在Silverlight2.0和VS2008环境中调试通过。本文参照了部分网络资料,希望能够抛砖引玉,大家共同学习。
(转载本文请注明出处)
Tag标签: Silverlight,WebService