【问题标题】:Blazor InputSelect binding value and updating another on selectBlazor InputSelect 绑定值并在选择时更新另一个
【发布时间】:2023-03-29 22:31:01
【问题描述】:

在我的 InputSelect 中,我需要能够绑定一个值并在选项选择/单击时更新该值和另一个值。

我的对象是什么样子的:

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

输入选择:

<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" />

所以office[0].Id 绑定到 InputSelect,但是在从办公室列表中选择一个选项时,它将同时更新 id 和名称。

【问题讨论】:

    标签: c# blazor


    【解决方案1】:

    如果 Account.Office[0] 与您的数组项的模型相同,我只需设置整个对象。

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

    如果它们不是同一个模型,我会使用一种方法:

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

    请注意,我现在正在工作,所以请原谅任何拼写错误或不准确之处。您可能需要稍微调整一下,但希望这个想法足够清晰。

    【讨论】:

    • 这是否涉及不使用 SelectInput 组件?因为我在使用 SelectInput 并将值绑定到它时发现 @onselect 没有被击中。 Plus office 与 Account.Office[0] 中使用的模型相同。
    • 我几乎只使用原版元素,没有看到任何不良影响,除了我想要一种验证多个输入的机制的实际表单。
    【解决方案2】:

    我留下了另一个答案,因为看看我错在哪里可能会有用。当我检查时,我意识到&lt;option&gt; 标签上的事件不会触发,甚至包括 onclick。

    尝试以下方法。您可能需要为 System.Linq 添加一个 using。

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

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 1970-01-01
      • 2021-03-18
      • 2016-02-26
      • 2021-08-24
      • 1970-01-01
      • 2021-04-04
      • 2021-05-16
      • 1970-01-01
      相关资源
      最近更新 更多