在<select>
中进行选择后,我需要能够运行一个函数。问题是我也与@bind绑定在一起,当我尝试使用@onchange时,我收到一条错误消息,指出它已经被@bind使用。我尝试使用@onselectionchange,但这不执行任何操作(不运行该功能)。我可能会忘记@bind,而只是将@onchange分配给一个函数,但是我不确定如何将所选值传递给该函数。
我有以下代码:
<select @bind="@SelectedCustID" @ @onchange="@CustChanged" class="form-control">
@foreach (KeyGuidPair i in CustList)
{
<option value="@i.Value">@i.Text</option>
}
</select>
谢谢。
答案 0 :(得分:4)
@bind
本质上等同于同时拥有value
和@onchange
,例如:
<input @bind="CurrentValue" />
等效于:
<input value="@CurrentValue" @onchange="@((ChangeEventArgs e) => CurrentValue = e.Value.ToString())" />
由于您已经定义了@onchange
,因此无需添加@bind
,而只需添加value
即可避免冲突:
<select value="@SelectedCustID" @onchange="@CustChanged" class="form-control">
@foreach (KeyGuidPair i in CustList)
{
<option value="@i.Value">@i.Text</option>
}
</select>
来源:https://docs.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-3.1
答案 1 :(得分:3)
这似乎是一个普遍的困惑。首先,您不能使用@onchange
,因为@bind
将在内部使用它。您应该能够从CustChanged
属性的设置器中访问选定的值。根据您要对CustChanged
进行的操作,您甚至无需手动检查此值的更新时间。例如,如果您打算在UI中直接或间接(在Linq之内或其他方式)使用CustChanged
,则在更改CustChanged
时,UI会自动以<select>
值进行更新。因此,对于大多数用例,我认为不需要检查其更新时间。
要使用@onchange
,可以将其绑定到类似以下的函数:
public void OnUpdated(ChangeEventArgs e)
{
var selected = e.Value;
}
答案 2 :(得分:3)
您可以完全避免使用@bind
(如果您使用的是foreach
):
<select @onchange=@(x => ...)>
@foreach (var option in _options) {
<option value=@option.Id selected=@(SelectedId == option.Id)>@option.Name</option>
}
</select>
---
public int SelectedId { get; set; }
一些肮脏的细节:尝试在服务器端Blazor中使用F#时,我得到一些奇怪的行为。简而言之,将List
选项设置为Entity Framework查询的结果(映射到记录列表)将无法正确@bind
,而是使用C#类和没有F#记录 did 的工作。但这并不是由于它是记录,因为如果我将列表设置为EF查询,然后立即将其设置为虚拟记录列表,它仍然不能正确@bind
-但它如果我注释掉EF行,会起作用。
答案 3 :(得分:1)
我的建议是,如果可能的话,在表单元素周围使用EditForm包装器。然后,您可以在一处检测到任何表单元素的更改。例如,这对于一堆搜索过滤器很有用。任何过滤器的任何更改都应触发另一次数据查询,等等。
如何在表单更改时触发事件的示例在这里:
答案 4 :(得分:1)
请检查此示例。它使用 @bind ,但是在设置该值时会触发 @onchange 事件
<div class="form-group">
<label for="client">Client Name</label>
<select id="client" @bind="CheckSelected" class="form-control">
<option value="selected1">selected1</option>
<option value="selected2">selected2</option>
</select>
</div>
@code { private string selectedItem {get; set;} private string CheckSelected { get { return selectedItem; } set { ChangeEventArgs selectedEventArgs = new ChangeEventArgs(); selectedEventArgs.Value = value; OnChangeSelected(selectedEventArgs); } } private void OnChangeSelected(ChangeEventArgs e) { if (e.Value.ToString() != string.Empty) { selectedItem = e.Value.ToString(); } } }
答案 5 :(得分:0)
<input @bind="MyProperty" />
@code {
private string myVar;
public string MyProperty
{
get { return myVar; }
set
{
myVar = value;
SomeMethod();
}
}
private void SomeMethod()
{
//Do something
}
}
答案 6 :(得分:0)
<div class="form-group">
<label for="client">Client Name</label>
<select class="form-control" @onchange="@((e) => { myVar = e.Value.ToString(); MyMethod(); })">
<option value="val1">val1</option>
<option value="val2">val2</option>
</select>
</div>
这就是我在@onchange 事件中调用方法时设置属性的方式。
-Blazor 服务器 -Dotnet 核心 3.1