【问题标题】:What is the best way to bind dynamics values in blazor在 blazor 中绑定动态值的最佳方法是什么
【发布时间】:2020-07-01 14:35:23
【问题描述】:

我正在使用 Dictionary 来存储一些选项,键是选项的名称,你猜的值是对应选项的值。

在我的剃须刀文件中,我有这段代码:

@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
  • 好像值是只读类型的,不能修改,至少razor文件里不能修改
  • 尝试绑定templates.templatesList[SelectionValue][option.Key]
  • @Vi100 键和值是只读的,因此在对象类之外很难超越它,我提出了一个可以正常工作的临时解决方案。

标签: c# blazor blazor-server-side asp.net-blazor


【解决方案1】:

我对下一个谷歌员工的解决方案:

绑定值的另一种方法是使用@onchange 选项,如下所述:https://docs.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-3.1

所以,我将代码更改如下:

在剃刀文件中:

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

我不知道这样做是否最干净,但它完美地完成了这项工作。

【讨论】:

  • 你如何重置值?
猜你喜欢
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
  • 2023-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多