You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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时触发空引用报错,可以做如下处理:

  1. 模型层面初始化默认值
    在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; }
}
  1. 页面层面做空值兼容
    直接在Razor代码中使用空条件运算符,空值时显示默认占位:
<th>日间温度:@(w.temp?.day.ToString("F1") ?? "暂无数据") °F</th>

内容的提问来源于stack exchange,提问作者Adam Cushing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:18:03