Reputation: 27
I am currently learning the basics of ASP.NET Core and C# and recently built a Blazor Server App to serve as a crude weather dashboard. After calling the desired weather web API in my web browser, I copied and pasted the returned raw data into my app through the 'paste JSON as classes' feature and then edited down the classes I want to target into two separate models as follows:
public class WeatherForecastModel
{
public DayForecastModel[] daily { get; set; }
}
and
public class DayForecastModel
{
public int sunrise { get; set; }
public int sunset { get; set; }
public Temp temp { get; set; }
public Feels_Like feels_like { get; set; }
}
public class Temp
{
public float day { get; set; }
public float min { get; set; }
public float max { get; set; }
}
In my razor page, I am able to successfully iterate over properties in the DayForecastModel and display them in my table doing the following:
<tbody>
@foreach (var w in forecast.daily)
{
<tr>
<th>@w.sunrise</th>
<th>@w.sunset</th>
</tr>
}
</tbody>
for reference, my 'forecast' variable is defined elsewhere as follows:
forecast = await client.GetFromJsonAsync<WeatherForecastModel>("https://api.openweathermap.org/data/2.5/onecall?lat=36.0999&lon=-80.2442&exclude={part}&appid={appid}&units=imperial");
What I can't figure out is how to access the properties contained in the 'Temp' class, which is itself contained inside the DayForecastModel class, so I can display things like 'day', 'min', and 'max'.
Apologies if this too convoluted of a question, I am very new to all of this. I'm more than happy to add any additional code that would help clarify the issue.
Upvotes: 1
Views: 381
Reputation: 273464
This ought to work:
<tr>
<th>@w.sunrise</th>
<th>@w.sunset</th>
<td>@w.temp?.day</td>
</tr>
The ?
in w.temp?.day
allows for temp == null
. If that is the case you have to fix it somwhere else.
HTML note: <th>
is for headers, you probably want <td>
instead.
Upvotes: 2