es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

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,>

Tags:  , ,

Answer

  1. Avatar for davy.ai

    Para solucionar el problema de que el modelo MyLocation sea nulo al hacer clic en el botón Save, puedes usar el atributo bind-value:event con el valor oninput. 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:

    @using Model
    
    <select bind-value="@MyLocation.CountryCode" bind-value:event="oninput" @onchange="@CountryChanged">
    @if (string.IsNullOrEmpty(MyLocation.CountryCode) == true)
    {
         <option value="0" selected="">[Elegir uno...]</option>
    }
    
    @foreach (var item in Countries)
    {
         <option value="@item.Key">@item.Value</option>
    }
    </select>
    <br>
    <select bind-value="@MyLocation.CityCode" bind-value:event="oninput">
    @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");
    
        return base.OnInitializedAsync();
    }
    
    private async Task CountryChanged(ChangeEventArgs e)
    {
        MyLocation.CountryCode = e.Value.ToString();
        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 ya no es nulo
    }
    }
    

    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ón Save.</string,></string,></string,></string,>

Comments are closed.