一步一步学Silverlight 2系列(13):数据与通信之WebRequest
概述
Silverlight 2 Beta 1版本發布了,無論從Runtime還是Tools都給我們帶來了很多的驚喜,如支持框架語言Visual Basic, Visual C#, IronRuby, Ironpython,對JSON、Web Service、WCF以及Sockets的支持等一系列新的特性。《一步一步學Silverlight 2系列》文章帶您快速進入Silverlight 2開發。
本文將簡單介紹在Silverlight 2中如何使用WebRequest進行數據的提交和獲取。
簡單示例
在本文中,我們仍然使用在一步一步學Silverlight 2系列(12):數據與通信之WebClient中用過的示例,只不過稍微做一點小的改動,使用WebRequest提交書籍編號數據,并根據書籍號返回價格信息。最終運行的結果如下圖:
編寫界面布局,XAML如下:
<Grid Background="#46461F"><Grid.RowDefinitions><RowDefinition Height="40"></RowDefinition><RowDefinition Height="*"></RowDefinition><RowDefinition Height="40"></RowDefinition></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition></ColumnDefinition></Grid.ColumnDefinitions><Border Grid.Row="0" Grid.Column="0" CornerRadius="15"Width="240" Height="36"Margin="20 0 0 0" HorizontalAlignment="Left"><TextBlock Text="書籍列表" Foreground="White"HorizontalAlignment="Left" VerticalAlignment="Center"Margin="20 0 0 0"></TextBlock></Border><ListBox x:Name="Books" Grid.Row="1" Margin="40 10 10 10"SelectionChanged="Books_SelectionChanged"><ListBox.ItemTemplate><DataTemplate><StackPanel><TextBlock Text="{Binding Name}" Height="32"></TextBlock></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox><Border Grid.Row="2" Grid.Column="0" CornerRadius="15"Width="240" Height="36" Background="Orange"Margin="20 0 0 0" HorizontalAlignment="Left"><TextBlock x:Name="lblPrice" Text="價格:" Foreground="White"HorizontalAlignment="Left" VerticalAlignment="Center"Margin="20 0 0 0"></TextBlock></Border> </Grid>編寫HttpHandler,注意我使用了context.Request.Form["No"],在后面我們將使用WebRequest在RequestReady方法中將數據寫入請求流:public class BookHandler : IHttpHandler {public static readonly string[] PriceList = new string[] { "66.00","78.30","56.50","28.80","77.00"};public void ProcessRequest(HttpContext context){context.Response.ContentType = "text/plain";context.Response.Write(PriceList[Int32.Parse(context.Request.Form["No"])]);}public bool IsReusable{get{return false;}} }在界面加載時綁定書籍列表,關于數據綁定可以參考一步一步學Silverlight 2系列(11):數據綁定。
private void UserControl_Loaded(object sender, RoutedEventArgs e) {List<Book> books = new List<Book>() { new Book("Professional ASP.NET 3.5"),new Book("ASP.NET AJAX In Action"),new Book("Silverlight In Action"),new Book("ASP.NET 3.5 Unleashed"),new Book("Introducing Microsoft ASP.NET AJAX")};Books.ItemsSource = books; }接下來在SelectionChanged事件中實現用戶選擇書籍時,我們使用WebRequest提交書籍編號,并且獲得價格數據,仍然采用異步模式,提供RequestReady和ResponseReady兩個回調函數:
private string bookNo;void Books_SelectionChanged(object sender, SelectionChangedEventArgs e) {bookNo = Books.SelectedIndex.ToString();Uri endpoint = new Uri("http://localhost:49955/BookHandler.ashx");WebRequest request = WebRequest.Create(endpoint);request.Method = "POST";request.ContentType = "application/x-www-form-urlencoded";request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);request.BeginGetResponse(new AsyncCallback(ResponseReady), request); }實現RequestReady方法,將書籍的編號寫入請求流中。
void RequestReady(IAsyncResult asyncResult) {WebRequest request = asyncResult.AsyncState as WebRequest;Stream requestStream = request.EndGetRequestStream(asyncResult);using (StreamWriter writer = new StreamWriter(requestStream)){writer.Write(String.Format("No={0}", bookNo));writer.Flush();} }實現ResponseReady方法,顯示返回的結果。
void ResponseReady(IAsyncResult asyncResult) {WebRequest request = asyncResult.AsyncState as WebRequest;WebResponse response = request.EndGetResponse(asyncResult);using (Stream responseStream = response.GetResponseStream()){StreamReader reader = new StreamReader(responseStream);lblPrice.Text = "價格:" + reader.ReadToEnd();} }最后運行的結果如下:
用戶選擇一本書籍后,將顯示其價格:
結束語
本文簡單介紹了在Silverlight 2中如何使用WebRequest提交和獲取數據,你可以從這里下載示例程序。
下一篇:一步一步學Silverlight 2系列(14):數據與通信之WCF
總結
以上是生活随笔為你收集整理的一步一步学Silverlight 2系列(13):数据与通信之WebRequest的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MOSS publishing功能:创建
- 下一篇: 启用新域名:ju690.com --聚了