Blazor 0.2.1预发布版Select下拉框OnChange事件触发问题求助
Blazor 0.2.1中Select下拉框绑定OnChange事件的正确姿势
我懂你在Blazor 0.2.1版本里搞Select下拉框的onchange事件时卡壳了——你现在用的是原生HTML的事件写法,这在Blazor里根本行不通,不仅没法正确触发你写的dostuff()方法,搞不好页面一加载就直接执行了,完全不是你要的“选中变化时触发”的效果。
咱们来一步步改对:
1. 先修正事件绑定的语法
Blazor早期版本(比如0.2.1)的事件绑定需要用@来关联组件内的C#方法,不能直接写原生的onchange="(dostuff())"。
方式一:带参数的方法绑定
首先把你的dostuff方法改成接收ChangeEventArgs参数的形式,这样还能拿到选中的具体值:
void dostuff(ChangeEventArgs e) { var selectedTemplate = e.Value.ToString(); Console.WriteLine($"选中了:{selectedTemplate},first spot is firing"); // 你的其他业务逻辑 }
然后修改Select的代码:
<select class="form-control d-flex" onchange="@dostuff"> @foreach (var template in templatestate.templates) { <option value="@template.Name">@template.Name</option> } </select>
这里@dostuff是把方法作为委托传递给onchange事件,只有当选中项变化时才会触发。
方式二:无参方法的lambda包装
如果你不想给方法加参数,也可以用lambda表达式把无参方法包起来:
<select class="form-control d-flex" onchange="@(() => dostuff())"> @foreach (var template in templatestate.templates) { <option value="@template.Name">@template.Name</option> } </select>
对应的方法保持你原来的无参形式就行:
void dostuff() { Console.WriteLine("first spot is firing"); // 其他逻辑 }
2. 额外选项:双向绑定+属性变更触发
如果你不仅要触发事件,还需要绑定选中的值,可以用Blazor的@bind语法,然后在属性的setter里调用你的方法:
// 组件内定义绑定属性 private string _selectedTemplateName; public string SelectedTemplateName { get => _selectedTemplateName; set { _selectedTemplateName = value; dostuff(); // 选中值变化时自动调用方法 } }
对应的Select代码改成:
<select class="form-control d-flex" @bind="@SelectedTemplateName"> @foreach (var template in templatestate.templates) { <option value="@template.Name">@template.Name</option> } </select>
核心问题就是你一开始用了原生HTML的事件写法,没遵循Blazor的组件事件绑定规则,按照上面的方式改完就能正常触发事件啦。
内容的提问来源于stack exchange,提问作者Grand Masta1
相关产品推荐
相关产品推荐

