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

Blazor使用InputSelect时触发NullReferenceException空引用异常

Blazor InputSelect 组件渲染抛出 NullReferenceException 问题排查

问题表现

  • Razor组件中使用InputSelect时,控制台持续抛出System.NullReferenceException(未将对象引用设置到对象的实例)
  • 异常堆栈指向Add.razor文件第18行的InputSelect渲染逻辑,无法直接定位错误点

异常堆栈

System.NullReferenceException: Object reference not set to an instance of an object.
at VidaConfortoApplication.Client.Pages.ServiceTypes.Add.b__0_7(RenderTreeBuilder __builder3) in C:\repos\sources\VidaConfortoTese\src\VidaConfortoApplication\VidaConfortoApplication\Client\Pages\ServiceTypes\Add.razor:line 18
at Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.AddContent(Int32 sequence, RenderFragment fragment)
at Microsoft.AspNetCore.Components.Forms.InputSelect`1[[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].BuildRenderTree(RenderTreeBuilder builder)
at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)

相关代码

Add.razor 组件

<EditForm Model="@_model"  OnValidSubmit="OnValidSubmit">
    <DataAnnotationsValidator />
    <div class="form-row">
        <div class="form-group col">
            <label>Serviço pai</label>
            <InputSelect class="form-control" @bind-Value="@_model.ParentId">
                <option value="">--</option>
                @foreach (var service in _services)
                {
                    <option value="@service.Id">@service.Name</option>
                }
            </InputSelect>
            <label>@_serviceHierarchy</label>
            <ValidationMessage For="@(() => _model.ParentId)"/>
        </div>
    </div>
    <br />
    <div class="form-group">
        <button class="btn btn-primary">
            Save
        </button>
    </div>
</EditForm>

@code {
    private readonly AddServiceTypeViewModel _model = new();
    private IEnumerable<ServiceType> _services;

    protected override async Task OnInitializedAsync()
    {
        _services = await ServiceTypeService.GetAll();
    }
}

AddServiceTypeViewModel 类

public class AddServiceTypeViewModel
{
    [Required]
    public string Name { get; set; }
    public long? ParentId { get; set; }
    public string? Description { get; set; }
}

ServiceType 类

public class ServiceType
{
    public string Name { get; set; }
    public long? ParentId { get; set; }
    public ServiceType? Parent { get; set; }
    public string? PathToService { get; set; }
    public string? Description { get; set; }
    public DateTime? AddedWhen { get; set; }
    public DateTime? UpdatedWhen { get; set; }
    public long Id { get; set; }
}

触发原因

异常的直接触发点是首次渲染时_services为null:
Blazor组件在执行OnInitializedAsync时,遇到第一次await会先返回并触发一次组件渲染,此时ServiceTypeService.GetAll()的异步请求还未完成,_services字段没有被赋值,是null值。@foreach循环直接遍历null的IEnumerable<ServiceType>,就会抛出空引用异常,堆栈指向的第18行正好是foreach循环渲染option的位置,和现象完全匹配。
另外代码还存在一个潜在问题:InputSelect没有显式声明TValue为long?,默认识别到的绑定类型是long(非空值类型),后续选中空选项时,空字符串无法转换为long类型,会触发转换异常。

修复方法

  1. 初始化_services为空集合,避免首次渲染遍历null:
    将字段声明修改为
    private IEnumerable<ServiceType> _services = Enumerable.Empty<ServiceType>();
    
  2. 显式指定InputSelect的泛型类型为可空long,匹配绑定值的类型,解决空选项转换问题:
    将InputSelect的声明修改为
    <InputSelect TValue="long?" class="form-control" @bind-Value="@_model.ParentId">
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 07:18:17