因此,当选择下拉值更改时,我一直试图让一个简单的onchange触发。像这样:
<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");
_template = templatestate.templates.FirstOrDefault(x => x.Name ==
_template.Name);
Console.WriteLine("second spot is firing");
}
无论我如何尝试重新定位它,我得到它的结果是浏览器中的这个错误。
Uncaught Error: System.ArgumentException: There is no event handler with ID 0
有什么明显的东西和关键,我错过了吗?因为我有一个按钮onclick事件,可以在同一页面中正常工作。
您的答案应该在cshtml中:
<select onchange=@DoStuff>
@foreach (var template in templates)
{
<option value=@template>@template</option>
}
</select>
然后,您的@functions应该看起来像:
@functions {
List<string> templates = new List<string>() { "Maui", "Hawaii", "Niihau", "Kauai", "Kahoolawe" };
string selectedString = "Maui";
void DoStuff(ChangeEventArgs e)
{
selectedString = e.Value.ToString();
Console.WriteLine("It is definitely: " + selectedString);
}
}
您也可以只使用绑定...
<select bind="@selectedString">
但是onchange = @ DoStuff允许您执行选择逻辑。
以上答案对我不起作用,出现编译错误。
下面是我的工作代码。
@inject HttpClient httpClient
@if (States != null)
{
<select id="SearchStateId" name="stateId" @onchange="DoStuff" class="form-control1">
<option>@InitialText</option>
@foreach (var state in States)
{
<option value="@state.Name">@state.Name</option>
}
</select>
}
@code {
[Parameter] public string InitialText { get; set; } = "Select State";
private KeyValue[] States;
private string selectedString { get; set; }
protected override async Task OnInitializedAsync()
{
States = await httpClient.GetJsonAsync<KeyValue[]>("/sample-data/State.json");
}
private void DoStuff(ChangeEventArgs e)
{
selectedString = e.Value.ToString();
Console.WriteLine("It is definitely: " + selectedString);
}
public class KeyValue
{
public int Id { get; set; }
public string Name { get; set; }
}
}