I am new to learning how to implement open weather API. I don't fully know how to show data to razor view. So if I wanted to show temp how would I do it. I don't want to use viewbag to show data.
I am using a tuple in razor view to implement 2 models. The openweatherModel which takes zipcode as input. The other is RootObject which is a class inside Json.cs which holds json information like temp, coord, description etc.
Api
public class ApiController
{
public async Task<Json.RootObject> GetResult(int zipCode)
{
const string apiKey = "";
var client = new HttpClient();
var response = await client.GetAsync("http://api.openweathermap.org/data/2.5/weather?zip=" +
zipCode + ",us&APPID=" + apiKey);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Json.RootObject>(responseBody);
}
Home
[HttpGet]
public ActionResult Main()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Main(int zipCode)
{
var controller = new ApiController();
var rootObject = await controller.GetResult(zipCode);
var tuple = new Tuple<OpenWeatherMap, RootObject>(new OpenWeatherMap(), new RootObject());
return View(tuple);
}
Razor
@model Tuple<Weather.Models.OpenWeatherMap, Weather.HelperClasses.Json.RootObject>
<div>
@using (Html.BeginForm("Main", "Home", FormMethod.Post, new { @class = "container" }))
{
@Html.TextBoxFor(tuple =>tuple.Item1.zipCode, new {@Name = "zipCode", @class = "inputs", required = "Required", placeholder = "Enter ZipCode" })
<input id="submit" type="submit" value="Search" />
foreach (var items in Model.Item2.weather)
{
<h1>@items.description</h1>
}
}
</div>
RootObject
public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string @base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int timezone { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}