【发布时间】:2019-05-12 17:32:24
【问题描述】:
我正在使用天气 API,其中用户从视图中搜索特定城市或国家/地区的天气,控制器作为参数接收,有关天气的信息完全有效,但我无法从控制器返回所有这些信息以查看。
查看搜索
<form action="searchbyname" method="post">
<input type="text" name="weather" placeholder="Find your location...">
<input type="submit" value="Find">
</form>
控制器
public ActionResult searchbyname(string weather)
{
string appId = "f40a39abac667183c127adefffcf88ed";
string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&units=metric&APPID={1}", weather, appId);
using (WebClient client = new WebClient())
{
string json = client.DownloadString(url);
if (json.IndexOf("Error") == -1)
{
WeatherInfo weatherInfo = (new JavaScriptSerializer()).Deserialize<WeatherInfo>(json);
ViewBag.citycountry = weatherInfo.name + "," + weatherInfo.sys.country;
ViewBag.ImageUrl = string.Format("http://openweathermap.org/images/flags/{0}.png", weatherInfo.sys.country.ToLower());
ViewBag.des = weatherInfo.weather[0].description;
//weatherimage
ViewBag.ImageUrl = string.Format("http://openweathermap.org/img/w/{0}.png", weatherInfo.weather[0].icon);
ViewBag.temp = string.Format("{0}°С", Math.Round(weatherInfo.main.temp, 1));
}
}
return View();
}
查看应该显示哪些数据
<table id="tblWeather" border="0" cellpadding="0" cellspacing="0" style="display:none">
<tr>
<th colspan="2">
Weather Information
</th>
</tr>
<tr>
<td rowspan="3">
<img id="imgWeatherIcon" />
</td>
</tr>
<tr>
<td>
<span id="citycountry">@ViewBag.citycountry</span>
<img id="imageurl" src="@ViewBag.ImageUrl" />
<span id="des">@ViewBag.des</span>
</td>
</tr>
模型类
public class ClimateModel
{
public class WeatherInfo
{
public Coord coord { get; set; }
public Sys sys { get; set; }
public List<Weather> weather { get; set; }
public Main main { get; set; }
public int dt { get; set; }
public string name { get; set; }
}
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Sys
{
public string country { get; set; }
}
public class Weather
{
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
public int humidity { get; set; }
}
}
}
【问题讨论】:
-
为什么不像Model-View-Controller那样创建一个Model,而不是使用viewbag(从技术上讲它不是一个模型)。
-
@ErikPhilips 实际上我有模型类,也想使用它,但无法理解如何在控制器内部使用,因为模型类(天气信息)已经用于从 API 获取数据。你可以看到使用了 weatherinfo 对象。请告诉我如何使用。我编辑了我的问题,添加了模型类。
标签: c# asp.net-mvc razor openweathermap