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

Blazor WebAssembly中<select>的@onchange事件触发失败问题

问题分析与解决方案

核心问题1:HTML注释语法错误

你的<select>标签内使用了/* doesn't fire */这种CSS/JS风格的注释,但HTML的标准注释语法是<!-- 注释内容 -->。错误的注释格式会干扰浏览器对DOM的解析,导致Blazor无法正确绑定@onchange事件。

核心问题2:未处理"Default"选项的键不存在情况

当选择"select"(对应value="Default")时,代码尝试访问components[DropdownValue],但你的字典中没有"Default"这个键,会抛出KeyNotFoundException,直接中断事件处理逻辑,甚至导致后续UI更新失效。

修复后的完整代码

@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<h2>Dynamic Component</h2>

<select @onchange="ChangeValue"> <!-- 修复注释语法 -->
    <option value="Default">select</option>
    <option value="Weather">Weather</option>
</select>

@if(selectedType is not null)
{
    <div class="p-2 mt-2">
        <DynamicComponent Type="selectedType"/>
    </div>
}
else
{
    <h3>Waiting...</h3>
}
                
@code {
    private Type? selectedType;

    private Dictionary<String, Type> components = new Dictionary<string, Type>()
    {
        ["Weather"] = typeof(Weather)
    };
    

    public void ChangeValue(ChangeEventArgs e)
    {
        Console.WriteLine("entre");

        if (e.Value is string dropdownValue)
        {
            // 处理Default选项,避免键不存在异常
            selectedType = components.TryGetValue(dropdownValue, out var type) ? type : null;
        }
        else
        {
            selectedType = null;
        }
    }
}

额外检查点

  • 确保Weather组件已正确导入到当前页面的命名空间中,比如在页面顶部添加@using YourAppNamespace.Components(替换为你的项目实际命名空间)。
  • 打开浏览器开发者工具(F12)查看控制台,确认是否存在组件类型找不到等其他异常信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 00:05:12