【问题标题】:Blazor Dynamic Input Fields DataBindingBlazor 动态输入字段数据绑定
【发布时间】:2022-01-23 15:29:23
【问题描述】:

我正在尝试了解数据绑定,但无法找出实现这一目标的最佳方法。

我的组件很简单:

<button type="reset" class="btn btn-primary" @onclick="ResetValues">Reset values</button>

<br />

<div class="row">
@for(int i=1; i<=NumberOfContacts; i++)
{
    <div class="col">
        <input type="text" class="form-control input-md">
    </div>
}
</div>
@code{
    [Parameter]
    public int NumberOfContacts {get; set;}


    public void ResetValues()
    {
        // how to reset dynamically generated input field values
    }
}

//In Index page, I am simply going:
<Contacts NumberOfContacts="3" />

它正确生成了我定义的输入字段的数量(在参数内的索引页面上),但是我如何绑定值以便我能够读取它们并在重置按钮单击事件时清除它们?

【问题讨论】:

    标签: blazor


    【解决方案1】:
    <button type="reset" class="btn btn-primary" @onclick="ResetValues">Reset values</button>
    
    <br />
    
    <div class="row">
    @for(int i=0; i<NumberOfContacts; i++)
    {
        @* Never use the loop variable directly *@
        int local=i; 
    
        @* Add a key to help Blazor track things *@
        <div class="col bg-success" @key=local> 
            @* Bind to an array element *@
            <input type="text" class="form-control input-md" @bind=contacts[local]> 
        </div>
    }
    </div>
    
    @code{
        [Parameter]
        public int NumberOfContacts {get; set;}
    
        // Bind this to the inputs
        string[] contacts;
    
        protected override void OnInitialized()
        {
            // Make sure to initialise the contacts array
            ResetValues();
        }
    
        public void ResetValues()
        {
            contacts = new string[NumberOfContacts];        
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      相关资源
      最近更新 更多