WEB开发网
开发学院图形图像Flash 学Silverlight 2系列(13):数据与通信之WebRequ... 阅读

学Silverlight 2系列(13):数据与通信之WebRequest

 2008-10-03 11:36:06 来源:WEB开发网   
核心提示: private void UserControl_Loaded(object sender, RoutedEventArgs e){List<Book> books = new List<Book>() {new Book("Professional AS

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系列(13):数据与通信之WebRequest

用户选择一本书籍后,将显示其价格:

学Silverlight 2系列(13):数据与通信之WebRequest

结束语

本文简单介绍了在Silverlight 2中如何使用WebRequest提交和获取数据,你可以下载示例程序。

上一页  1 2 

Tags:Silverlight 系列 数据

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接