[英]How can I determine selected value in dropdown without using bind in Blazor?
I'm trying to do this all in C# but I may have to resort to JavaScript.我试图在 C# 中完成这一切,但我可能不得不求助于 JavaScript。
I have a dropdown that I want to do an onchange event.我有一个下拉列表,我想做一个 onchange 事件。 I can't bind the dropdown to the model as binding prevents the use of onchange.我无法将下拉列表绑定到 model,因为绑定会阻止使用 onchange。 I need to use the onchange event to modify some things on the screen depending on what is selected.我需要使用 onchange 事件根据所选内容修改屏幕上的某些内容。 Maybe some code will help.也许一些代码会有所帮助。
<select id="BrandSelected" @onchange="BrandIsChanged">
<option value="NewBrand">--Create New Brand--</option>
@foreach (var brand in Brands)
{
if(Model.BrandID == brand.BrandID)
{
<option value="@brand.BrandID" selected>@brand.Brand</option>
}
else
{
<option value="@brand.BrandID">@brand.Brand</option>
}
}
</select>
<label id="BrandLabel" hidden>New Brand</label>
<InputText id="NewBrandInput" @bind="NewBrandProp" hidden></InputText>
So I'm adding the option at the top to create a new brand.所以我在顶部添加了创建新品牌的选项。 This is an upsert so it's possible one of the brands may already be selected.这是一个 upsert,因此可能已经选择了其中一个品牌。 It will still be changeable on update.它仍然会在更新时更改。 It works if the user selects any of the existing brands but I want to be able to add a new brand if it does not exist in the dropdown.如果用户选择任何现有品牌,它就可以工作,但如果下拉列表中不存在新品牌,我希望能够添加它。 If in the BrandIsChanged method, the NewBrand has been selected, then I want to create a new brand with the value in the InputText.如果在 BrandIsChanged 方法中,已经选择了 NewBrand,那么我想用 InputText 中的值创建一个新品牌。 This means I will have to modify both the label and the InputText to be visible onchange if the selected value is NewBrand.这意味着如果选择的值为 NewBrand,我将不得不同时修改 label 和 InputText 以使 onchange 可见。 So, how can I determine in the BrandIsChanged method what the selected item (BrandSelected) value is?那么,如何在 BrandIsChanged 方法中确定所选项目 (BrandSelected) 的值是什么?
Other things that might be helpful:其他可能有帮助的事情:
@code{
//Populated on load in a method
private IEnumerable<T_IFS_BrandDTO> Brands { get; set; } = new List<T_IFS_BrandDTO>();
//The new brand, if user decides to enter one.
private string NewBrandProp { get; set; }
}
The onchange
event passes ChangeEventArgs
parameter to your event handler which you can use to get the selected value. onchange
事件将ChangeEventArgs
参数传递给您的事件处理程序,您可以使用它来获取选定的值。
<select id="BrandSelected" @onchange="BrandIsChanged">
...
</select>
@code {
private BrandIsChanged(ChangeEventArgs args)
{
if (args?.Value?.ToString() == "NewBrand")
{
// do stuff
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.