.net使用WebService获取天气预报

(1)新建个网站,将其命名为WeatherService

(2)右键程序根目录,添加Web引用,在服务地址填入:http://www.ayandy.com/Service.asmx ,

     在Web引用名输入obj ,然后添加引用。

(3)在Default.aspx页面中写入:

<div>
        省份:<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
        </asp:DropDownList>城市:<asp:DropDownList ID="DropDownList2" runat="server">
        </asp:DropDownList>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="获 取" />
    </div>
    <div style ="border :solid 1px #8daaf4;margin-top :5px;">
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
        <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label><br />
        <asp:Label ID="Label4" runat="server" Text="Label"></asp:Label><br />
        <asp:Label ID="Label5" runat="server" Text="Label"></asp:Label><br />
        <asp:Image ID="Image1" runat="server" />
      
    </div>

(4)在后置代码中写入:

        using System.Web.Services;
         using obj; //引用

         obj.Service myobj = new obj.Service(); //实例化

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindPro();
            BindCity();
            BindWeather();
        }
    }

    // 获得省份
    protected void BindPro()
    {
        string[] pro = myobj.getSupportProvince();
        for (int i = 1; i <= Int32.Parse(pro[0]); i++)
        {
            DropDownList1.Items.Add(new ListItem(pro[i].ToString(), pro[i].ToString()));
        }
    }
    //获得城市
    protected void BindCity()
    {
        DropDownList2.Items.Clear();
        string[] city = myobj.getSupportCity(DropDownList1.SelectedValue);
        for (int i = 1; i <= Int32.Parse(city[0]); i++)
        {
            DropDownList2.Items.Add(new ListItem(city[i].ToString(), city[i].ToString()));
        }
    }
    //天气预报
    protected void BindWeather()
    {
        string[] mystr = myobj.getWeatherbyCityName(DropDownList2.SelectedValue, theDayFlagEnum.Today);
        Label1.Text = mystr[1].ToString();
        Label2.Text = mystr[2].ToString();
        Label3.Text = mystr[3].ToString();
        string fengxaing = mystr[4];
        Label4.Text = Convert.ToString(fengxaing);
       
        Label5.Text = mystr[5].ToString();
        Image1.ImageUrl = mystr[6].ToString();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindCity();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        BindWeather();
    }

(5)web.config中写入:

<appSettings>
  <add key="obj.Service" value="http://www.ayandy.com/Service.asmx"/>
 </appSettings>

posted @ 2010-06-20 16:11  爱国者  阅读(839)  评论(1编辑  收藏  举报