微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SilverLight中 数据与通信之WebRequest

SilverLight中 数据与通信之WebRequest

 

1.       新建一个处理类BookHandler.ashx

public class BookHandler : IHttpHandler

    {

 

        public void ProcessRequest(HttpContext context)

        {

            //context.Response.ContentType = "text/plain";

            //context.Response.Write(PriceList[Int32.Parse(context.Request.QueryString["No"])]);

 

 

            context.Response.ContentType = "text/plain";

            context.Response.Write(PriceList[Int32.Parse(context.Request.Form["No"])]);

 

        }

 

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

 

 

        public static readonly string[] PriceList = new string[] {

        "66.00",

        "78.30",

        "56.50",

        "28.80",

        "77.00"

        };

}

 

2.      调用

前台代码:

<Grid x:Name="LayoutRoot" 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>

 

后台代码:

public partial class MainPage : UserControl

    {

        private string bookNo = "0";

 

        public MainPage()

        {

            InitializeComponent();

            Loaded += new RoutedEventHandler(MainPage_Loaded);

        }

 

        void MainPage_Loaded(object sender,RoutedEventArgs e)

        {

            List<Book> books = new List<Book>() {

            new Book("精通 ASP.NET 3.5"),

            new Book("ASP.NET AJAX 实践"),

            new Book("Silverlight 实践"),

            new Book("ASP.NET 3.5 Unleashed"),

            new Book("Introducing Microsoft ASP.NET AJAX")

              };

 

            Books.ItemsSource = books;

 

        }

 

        void Books_SelectionChanged(object sender,SelectionChangedEventArgs e)

        {

            bookNo = Books.Selectedindex.ToString();

            //这里涉及两个问题:

            //1.跨线程更新UI //可参考 http://www.cnblogs.com/RChen/archive/2008/07/25/1250948.html

            //2.跨域调用

            Uri endpoint = new Uri("http://localhost:4699/BookHandler.ashx");

            WebRequest request = WebRequest.Create(endpoint);

            request.Method = "POST";

            request.ContentType = "application/x-www-form-urlencoded";

            request.BeginGetRequestStream(new AsyncCallback(RequestReady),request);

 

        }

        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();

            }

            //

            request.BeginGetResponse(new AsyncCallback(ResponseReady),request);

        }

        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.dispatcher.BeginInvoke(new UpdatePriceDelegate(UpdatePrice),reader.ReadToEnd());

            }

 

        }

        private delegate void UpdatePriceDelegate(string price);

        private void UpdatePrice(string price)

        {

            lblPrice.Text = "价格:" + price;

        }

    }

 

    public class Book

    {

        public Book(string name)

        {

            this.Name = name;

        }

        public string Name

        {

            get;

            set;

        }

 

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐