Overview
The release of Silverlight 2 Beta 1 brings us a lot of surprises from Runtime and Tools, such as supporting the framework languages Visual Basic, Visual C #, IronRuby, Ironpython, A series of new features such as JSON, Web Service, WCF, and Sockets support. The one-step learning Silverlight 2 series article takes you to Silverlight 2 development quickly.
This article describes how to use WebRequest to submit and obtain data in Silverlight 2.
Simple Example
In this article, we still use the examples used in the data and communication WebClient step by step to learn Silverlight 2 series (12), but make a slight change, use WebRequest to submit the book number data and return the price information based on the book number. The final running result is as follows:
Compile the interface layout. The XAML is as follows:
<Grid Background = "# 46461F"> <Grid. rowDefinitions> <RowDefinition Height = "40"> </RowDefinition> <RowDefinition Height = "*"> </RowDefinition> <RowDefinition Height = "40"> </RowDefinition> </ grid. rowDefinitions> <Grid. columnDefinitions> <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 = "Books list "Foreground =" White "HorizontalAlignment =" Left "verticalignment =" 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 = "price: "Foreground =" White "HorizontalAlignment =" Left "verticalignment =" Center "Margin =" 20 0 0 0 "> </TextBlock> </Border> </Grid>
Compile HttpHandler. Note that I have used context. Request. Form ["No"]. Later we will use WebRequest to write data to the Request stream in the RequestReady method:
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; } }}
Bind the book list when loading the interface. For details about data binding, refer to step by step Silverlight 2 series (11): Data Binding.
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;}
When selecting a book in the SelectionChanged event, we use WebRequest to submit the Book Number and obtain the price data. We still use the asynchronous mode and provide two callback functions: RequestReady and 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); }
Implement the RequestReady method to write the book number into the request stream.
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(); }}
Implement the ResponseReady method to display the returned results.
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 = "Price:" + reader. readToEnd ();}}
The final running result is as follows:
After you select a book, the price is displayed:
Conclusion
This article briefly introduces how to use WebRequest to submit and obtain data in Silverlight 2. You can download the sample program from here.
Next article: Step by Step Silverlight 2 series (14): data and communication-based WCF