Home > Software design >  How can I determine selected value in dropdown without using bind in Blazor?
How can I determine selected value in dropdown without using bind in Blazor?

Time:09-20

I'm trying to do this all in C# but I may have to resort to JavaScript.

I have a dropdown that I want to do an onchange event. I can't bind the dropdown to the model as binding prevents the use of onchange. I need to use the onchange event to modify some things on the screen depending on what is selected. 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. 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. This means I will have to modify both the label and the InputText to be visible onchange if the selected value is NewBrand. So, how can I determine in the BrandIsChanged method what the selected item (BrandSelected) value is?

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; }
}

CodePudding user response:

The onchange event passes ChangeEventArgs parameter to your event handler which you can use to get the selected value.

<select id="BrandSelected" @onchange="BrandIsChanged">
    ...
</select>

@code {
    private BrandIsChanged(ChangeEventArgs args)
    {
         if (args?.Value?.ToString() == "NewBrand")
         {
             // do stuff
         }
    }
}
  • Related