Blazor Server调用Web API后如何迭代访问返回的嵌套类属性
你可以直接通过链式访问的方式读取嵌套的Temp类属性,在已有的循环变量w后追加.temp.属性名即可调用对应温度值。
修改后的Razor页面表格代码示例如下:
<tbody> @foreach (var w in forecast.daily) { <tr> <th>@w.sunrise</th> <th>@w.sunset</th> <!-- 新增温度字段展示 --> <th>日间温度:@w.temp.day °F</th> <th>最低温度:@w.temp.min °F</th> <th>最高温度:@w.temp.max °F</th> </tr> } </tbody>
额外优化建议
为了避免API返回数据异常导致temp为null时触发空引用报错,可以做如下处理:
- 模型层面初始化默认值
在DayForecastModel类中给temp属性设置初始值:
public class DayForecastModel { public int sunrise { get; set; } public int sunset { get; set; } public Temp temp { get; set; } = new Temp(); public Feels_Like feels_like { get; set; } }
- 页面层面做空值兼容
直接在Razor代码中使用空条件运算符,空值时显示默认占位:
<th>日间温度:@(w.temp?.day.ToString("F1") ?? "暂无数据") °F</th>
内容的提问来源于stack exchange,提问作者Adam Cushing
相关产品推荐
相关产品推荐

