简体   繁体   中英

Blazor InputSelect binding value and updating another on select

In my InputSelect I need to be able to bind a value and on option select/click update both that value and another.

What my object looks like:

public class AccountModel
{
    [Required(ErrorMessage = "Please enter an Office")]
    public Office[] Office { get; set; }
}

public class Office
{
    public string Id { get; set; }
    public string Name { get; set; }

    public Office()
    {
            
    }

    public Office(string _id, string _name)
    {
        Id = _id;
        Name = _name;
    }
}

InputSelect:

<p class="m-0 form-details-lbl">Office</p>
        <InputSelect class="m-0 form-control edit-active"
                     @bind-Value="Account.Office[0].Id">
            <option selected disabled>Select Office</option>
                    @foreach (Office office in OfficeLoc)
            {
            <option value=@office.Id @onselect="() => Account.Office[0].Name = office.Name">@office.Name</option>
            }
        </InputSelect>
        <ValidationMessage For="() => Account.Office" />

So that office[0].Id is bound to the InputSelect, however on an option select from the list of offices it will update both the id and the name.

If Account.Office[0] is the same model as your array items, I'd just set the whole object.

<option value=@office.Id @onselect="() => Account.Office = office">@office.Name</option>

If they are not the same model, I'd use a method:

 <option value=@office.Id @onselect="() => SetOffice(office)">@office.Name</option>

@code {
     void SetOffice(Office newOffice){
             Account.Office[0].Id = newOffice.id;
             Account.Office[0].Name = newOffice.Name;
     }
}

Note I'm at work right now, so forgive any typos or inaccuracies. You might have to tweak it a little, but hopefully the idea is clear enough.

I left the other answer because seeing where I was wrong might be useful. When I checked, I realized that events on the <option> tag don't fire, including even onclick.

Try something like the following. You might need to add a using for System.Linq .

<select name="offices" id="offices" @onchange="SelectOffice">
    <option selected hidden>Select a room</option>
    @foreach (var office in AvailableOffices)
    {
        <option value=@office.ID>@office.Name</option>
    }
</select>

@code{
    Office SelectedOffice {get;set;} // i.e. Account.Office[0]
    List<Office> AvailableOffices {get; set;}

    void SelectOffice(ChangeEventArgs e)
    {
        SelectedOffice = AvailableOffices.Where(ao => ao.ID.ToString() == e.Value.ToString()).First();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM