`
weiyinchao88
  • 浏览: 1187868 次
文章分类
社区版块
存档分类
最新评论

学习笔记1(使用web服务实现各地天气预报查询)

 
阅读更多

源码下载地址:http://download.csdn.net/source/3447733

首先引用web服务 web引用名为:localhost

url:http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx

其次我做了两个实体类

一个是省份。一个是城市。

//省份实体类

public class Province
{
public string Name { get; set; }
public string Code { get; set; }
}

//城市实体类

public class City
{
public string CityName { get; set; }
public int CityCode { get; set; }
}

接下来是得到省市编号的类:GetCode

public class GetCode
{

//得到各省直辖市的名称及idweb服务提供的返回值有两种dataset和一维数组 本人使用的是数组
public static string[] GetProCode()
{

localhost.WeatherWS web = new localhost.WeatherWS();
string[] province = web.getRegionProvince();
return province;

}

//将得到的一维数组转化为实体对象集合
public static List<Province> GetPro()
{
string[] pro = GetProCode();
List<Province> lst = new List<Province>();
for (int i = 0; i < pro.Length; i++)
{
string[] p = pro[i].Split(',');
Province province = new Province();
province.Name = p[0];
province.Code = p[1];
lst.Add(province);
}
return lst;
}

//根据各省id得到该省各城市的名称及id
public static string[] GetCityCode(string id)
{
localhost.WeatherWS web = new localhost.WeatherWS();
string[] city = web.getSupportCityString(id);
return city;
}

//将得到的一维数组转化为实体对象集合

public static List<City> GetCity(string id)
{
string[] city = GetCityCode(id);
List<City> lst = new List<City>();
for (int i = 0; i < city.Length; i++)
{
string[] p = city[i].Split(',');
City c = new City();
c.CityName = p[0];
c.CityCode = Convert.ToInt32(p[1]);
lst.Add(c);
}
return lst;
}

//根据各城市id得到该城市的天气预报 返回值为一维数组
public static string[] GetWeather(string CityCode)
{
localhost.WeatherWS web = new localhost.WeatherWS();
string[] weather = web.getWeather(CityCode, "");
return weather;
}
}

表示层:

页面Weather.aspx只有两个DropDownList

分别为DropDownList1(省)和DropDownList2(市)

代码:

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BD();
}

}

private void BD()
{
List<Province> lst = GetCode.GetPro();
DropDownList1.DataSource = lst;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Code";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "--请选择--");
DropDownList2.Items.Insert(0, "--请选择--");
}
protected void DropDownList1_TextChanged(object sender, EventArgs e)
{
DropDownList2.Items.Clear();
string id = DropDownList1.SelectedValue;
List<City> lst = GetCode.GetCity(id);
foreach (var item in lst)
{
DropDownList2.Items.Add(new ListItem(item.CityName,item.CityCode.ToString()));
}
DropDownList2.Items.Insert(0, "--请选择--");
}
protected void DropDownList2_TextChanged(object sender, EventArgs e)
{
string[] weather = GetCode.GetWeather(DropDownList2.SelectedValue);
for (int i = 0; i < weather.Length; i++)
{
Response.Write(weather[i] + "<br>");
}
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics