我正在尝试从openweathermap API获取天气。 我想要在输入文本框后显示城镇的天气。 在这一刻,我有一个代码... 我是asp.net mvc的新手,培训非常紧张:(( 该代码正在运行。我需要在文本框中输入城市,而不是选择组合框。
控制器:
<img src="https://image.tmdb.org/t/p/w500/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg?api_key=05b735a5f79822f887889281f45b295a" alt="Fight Club">
查看:
public OpenWeatherMap FillCity() {
OpenWeatherMap openWeatherMap = new OpenWeatherMap();
openWeatherMap.Cities = new Dictionary<string, string>();
openWeatherMap.Cities.Add("New Delhi", "1261481");
openWeatherMap.Cities.Add("Abu Dhabi", "292968");
openWeatherMap.Cities.Add("Lahore", "1172451");
return openWeatherMap;
}
public ActionResult Index() {
OpenWeatherMap openWeatherMap = FillCity();
return View(openWeatherMap);
}
[HttpPost]
public ActionResult Index(OpenWeatherMap openWeatherMap, string cities)
{
openWeatherMap = FillCity();
if (cities != null) {
string apiKey = "MyAPIKey";
HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" +
cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest;
string apiResponse = "";
HttpWebResponse response = (HttpWebResponse)apiRequest.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
apiResponse = reader.ReadToEnd();
ResponseWeather rootObject = JsonConvert.DeserializeObject<ResponseWeather>(apiResponse);
StringBuilder sb = new StringBuilder();
sb.Append("<table><tr><th>Weather Description</th></tr>");
sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>");
sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>");
sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>");
sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + " °C</td></tr>");
sb.Append("<tr><td>Min Temperature:</td><td>" + rootObject.main.temp_min + " °C</td></tr>");
sb.Append("<tr><td>Max Temperature:</td><td>" + rootObject.main.temp_max + " °C</td></tr>");
sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>");
sb.Append("<tr><td>Weather:</td><td>" + rootObject.weather[0].description + "</td></tr>");
sb.Append("</table>");
openWeatherMap.apiResponse = sb.ToString();
}
else {
if (Request.Form["submit"] != null) {
openWeatherMap.apiResponse = "Select City";
}
}
return View(openWeatherMap);
}
@using (Html.BeginForm())
{<button id="reset" name="reset">Reset »</button>}
<div id="apiDiv">
<h4>Select the City for Weather Report</h4>
@using (Html.BeginForm())
{
foreach (var city in Model.Cities)
{
<span>
@Html.RadioButtonFor(m => m.Cities, city.Value) @city.Key
</span>
}
<button name="submit">Submit</button>
}
<div id="message">@(new HtmlString(Model.apiResponse))</div>
</div>
<!--script-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("input[id='Cities']").change(function () {
$(this).parents("#apiDiv").find
("span").css("background", "none");
$(this).parent().css("background", "#4CAF50");
});
});
</script>
感谢您的帮助。