【问题标题】:Get value of input field in table row on button click in Blazor在 Blazor 中单击按钮时获取表格行中输入字段的值
【发布时间】:2020-12-01 18:54:39
【问题描述】:

我在一组产品上呈现一个表格,每一行都有一个带有点击事件的按钮来传递该行的产品。这行得通。

我想要完成的是在同一个按钮上单击该行的输入字段的值:

<tbody>
    @foreach (var product in products)
    {
        <tr>
            <td>@product.Day</td>
            <td>@product.Name</td>
            <td>@product.Price</td>
            <td>
                <img src="images/@(product.Name).jpg" alt="" style="width:100px;" />
            </td>
            <td>
                <input type="text" id="amount" />
            </td>
            <td><button @onclick="(() => Add(product))" >Add</button></td>
        </tr>
    }
</tbody>

在后面的代码中我有以下方法(仅在放入产品时有效):

protected async Task Add(Product product)
{

}

如何更改输入字段(或将其替换为编辑表单中每一行的 InputText?)并将其传递给 Add 方法,如

protected async Task Add(Product product, int amount)
{

}

【问题讨论】:

    标签: blazor blazor-webassembly


    【解决方案1】:

    只需将输入的值绑定到字段或属性。然后你可以在你的方法中使用它:

    <input type="text" id="amount" @bind-value="@_amount" />
    
    @code {
        private int _amount = 0;
        
        protected async Task Add(Product product)
        {
            if (_amount > 0)
                    ...
        }
    }
    

    【讨论】:

    • 不幸的是,在调用 Add 方法后,每行的输入都会更改为 _amount 中的内容。我当然可以将它设置回 0,但我认为有一种更优雅的方法可以做到这一点,比如将它作为参数传递给按钮的 onclick。
    【解决方案2】:

    我尝试了一种不同的方法并将 Amount 属性添加到 Product 类:

    public class Product
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
        public DayOfWeek Day { get; set; }
        public int Amount { get; set; }
    }
    

    在我的页面中,我让它像这样工作:

    @foreach (var product in products)
    {
        <tr>
            <td>@product.Day</td>
            <td>@product.Name</td>
            <td>@product.Price</td>
            <td>
                <img src="images/@(product.Name).jpg" alt="" style="width:100px;" />
            </td>
            <td>            
                <input type="text" @bind-value="@product.Amount" />
            </td>
            <td><button @onclick="(() => Add(product))" >Add</button></td>
        </tr>
    }
    

    在我的函数中,我获取输入字段的值,并在处理完金额后将其设置回 0:

    protected async Task Add(Product product)
    {
        // do something useful with the amount and set it back to 0
        product.Amount = 0;
    }
    

    不过,如果有其他解决方案可以将其作为参数传递,我想知道。

    【讨论】:

    • 是的,有...我只是要发布与您的解决方案相同的内容。我认为这是正确的方法......添加一个新字段。简约中的优雅。为什么你将 product.Amount 设置为 0 呢?
    • 否则金额停留在第一个已放入相应输入字段中。实际上,与其使用 Amount Quantity,不如为其命名。
    • 也许,另一种方法是将行提取为单个组件并将输入字段用作ElementReference(@ref 关键字)。如果您不想在子组件中包含 Add Method,可以将 Action 或 Func 作为参数传递给子组件。
    猜你喜欢
    • 2019-12-09
    • 2021-07-26
    • 2021-08-25
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多