Propiedades del modelo no vinculadas a menús desplegables en Blazor.
Tengo 2 dropdowns en cascada:
El problema es que cuando hago clic en el botón “Guardar” mi modelo estaría vacío. No puedo usar “bind-value” en mis dropdowns porque no puedo usar el evento “onchange”. ¿Cómo puedo tener la funcionalidad de cascada y al mismo tiempo propiedades de enlace?
Códigos:
“`razor
@using Model
<select value="@MyLocation.CountryCode" @onchange="@CountryChanged">
@if (string.IsNullOrEmpty(MyLocation.CountryCode) == true)
{
<option value="0" selected="">[Seleccione una opción…]</option>
}
@foreach (var item in Countries)
{
<option value="@item.Key">@item.Value</option>
}
</select>
<br>
<select value="@MyLocation.CityCode">
@foreach (var item in CountryCities)
{
<option value="@item.Key">@item.Value</option>
}
</select>
<br>
<button class="btn btn-success" @onclick="() => HandleSave()">Guardar</button>
@code {
public Location MyLocation { get; set; } = new Location();
private Dictionary<string, string=""> Countries { set; get; } = new Dictionary<string, string="">();
private Dictionary<string, string=""> CountryCities { set; get; } = new Dictionary<string, string="">();
protected override Task OnInitializedAsync()
{
Countries.Add("01", "Alemania");
Countries.Add("02", "Japón");
Countries.Add("03", "Inglaterra");
<pre><code>return base.OnInitializedAsync();
</code></pre>
}
private async Task CountryChanged(ChangeEventArgs e)
{
CountryCities.Clear();
switch (e.Value.ToString())
{
case "01":
CountryCities.Add("001", "Múnich");
break;
case "02":
CountryCities.Add("002", "Tokio");
break;
case "03":
CountryCities.Add("003", "Manchester");
break;
}
}
private void HandleSave()
{
var Country = MyLocation.CountryCode; <— CountryCode es nulo
}
}
“`</string,></string,></string,>
davy.ai
Para solucionar el problema de que el modelo
MyLocation
sea nulo al hacer clic en el botónSave
, puedes usar el atributobind-value:event
con el valoroninput
. Esto actualizará la propiedad del valor seleccionado en el modelo cada vez que se realice un cambio en el menú desplegable.Aquí tienes una versión actualizada del código con el atributo
bind-value:event
agregado a ambos menús desplegables:Ahora, cuando selecciones un valor del menú desplegable, la propiedad correspondiente en el modelo
MyLocation
se actualizará y no será nula al hacer clic en el botónSave
.</string,></string,></string,></string,>