什么是在Blazor中绑定动态值的最佳方法?

6

我正在使用一个 Dictionary<string,string> 来存储一些选项,键是选项的名称,而值是相应选项的值。

在我的 Razor 文件中,我有以下代码:

@foreach (KeyValuePair<string, string> option in templates.templatesList[SelectionValue])
{
    <tr>
        <td>@option.Key</td>
        <td><input type="text"/></td>
    </tr>
}

我想要做的是将文本输入框中的值存储到我的字典的正确值中,但遗憾的是我们不能使用@bind = @option.Value。


为什么不能使用 @bind = option.Value? - enet
似乎该值是只读类型,您无法修改它,至少在 Razor 文件中不行。 - Amine Tagui
1
尝试绑定到模板。templatesList [SelectionValue] [option.Key] - Vi100
@Vi100 键和值是只读的,因此在对象类之外很难操纵它们,我提出了一个临时解决方案,可以很好地解决这个问题。 - Amine Tagui
1个回答

9

我为下一个 Google 工程师提供了解决方案:

另一种绑定值的方式是使用 @onchange 选项,就像这里所描述的那样:https://learn.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-3.1

因此,我将代码更改如下:

在 Razor 文件中:

@foreach (KeyValuePair<string, string> option in templates.templatesList[SelectionValue])
{

    <tr>
        <td><label>@option.Key</label></td>
        <td><input type="text" @onchange="@((ChangeEventArgs __e) => changeOption(__e,option.Key))" /></td>
    </tr>

}

public void changeOption(ChangeEventArgs __e, string key)
{
    templates.changeValue(SelectionValue, key, __e.Value.ToString());
}

在我的对象类(模板)中

public void changeValue(string template, string option, string value)
    {
        this.templatesList[template][option] = value;
    }

我不确定这是否是最干净的方法,但它完美地完成了工作。

你如何重置数值? - Nk54

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接