天天看點

Silverlight調用自定義的Web Service從資料庫擷取資料進行頁面綁定

    Silverlight調用WebService隻能使用異步方式調用。所謂異步方式調用就是讓調用方法的主線程不必同步等待在這個函數調用上,進而允許主線程繼續執行它下面的代碼。

    Silverlight調用自定義的WebService分為四個步驟:

   (1)、建立自定義的WebService

   (2)、實作WebService

   (3)、在Silverlight項目中添加服務引用

   (4)、使用異步方式調用WebService

下面舉例介紹:

    比如說在MSSQL2000中建立一個名為SilverlightDB的資料庫,裡面包含一張表Product,裡面有2個字段Name和Price,舉例說明字段就随便用兩個意思意思下。

    在Web.Config檔案中配置資料庫連接配接字元串

   <appSettings>

    <add key="ConnectionString" value="Data Source=.;uid=sa;pwd=111111;Database=SilverlightDB"/>

  </appSettings>

  接着定義一個和Product表對應的實體類Product.cs

  [Serializable]

    public class Product

    {

        public string Name { get; set; }

        public double Price { get; set; }

    }

  再接着是添加一個Web服務,檔案名為ProductService.asmx

  在其中添加一個擷取産品清單的方法GetAllProduct

         [WebMethod]

        public List<Product> GetAllProduct()

        {

            List<Product> products= new List<Product>();

            //這裡是從資料庫擷取資料,方式可以是ADO.NET、LINQ to SQL或者是ADO.NET Entity Framework,以下是用最簡單的ADO.NET來實作的

            string connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];

            using (SqlConnection con = new SqlConnection(connectionString))

            {

                con.Open();

                string strSQL = "select * from Product";

                SqlCommand cmd = new SqlCommand(strSQL, con);

                SqlDataReader data = cmd.ExecuteReader();

                while (data.Read())

                {

                    Product product = new Product();

                    product.Name = data["Name"].ToString();

                    product.Price = double.Parse(data["Price"].ToString());

                    products.Add(product);

                }

            }

            return products;

        }

   前台顯示頁面MainPage.xaml中添加一個ListBox用于顯示資料

   <ListBox x:Name="myBooks" Margin="101,144,158,124">

   <ListBox.ItemTemplate>

    <DataTemplate>

     <StackPanel>

      <TextBlock Text="{Binding Name}"></TextBlock>

      <TextBlock Text="{Binding Price}"></TextBlock>

      <TextBlock Text="---------------------------------------------------------------"></TextBlock>

     </StackPanel>

    </DataTemplate>

   </ListBox.ItemTemplate>

  </ListBox>

 在MainPage.xaml.cs檔案中編寫調用WebService的代碼進行資料綁定

private void LayoutRoot_Loaded(object sender, System.Windows.RoutedEventArgs e)

           // TODO: Add event handler implementation here.

            ProductServiceReference.ProductServiceSoapClient client = new NetworkSample.ProductServiceReference.ProductServiceSoapClient();

            //注冊調用成功事件

            client.GetAllProductCompleted += new EventHandler<NetworkSample.ProductServiceReference.GetAllProductCompletedEventArgs>(OnGetAllProductCompleted);

            client.GetAllProductAsync();

        private void OnGetAllProductCompleted(object sender, NetworkSample.ProductServiceReference.GetAllProductCompletedEventArgs e)

            //檢測調用是否成功

            if (e.Error != null)

                return;

            myBooks.ItemsSource = e.Result;

至此,一個Silverlight調用自定義的WebService的案例就做好了。