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

Ami*_*gui 7 c# blazor blazor-server-side asp.net-blazor

我使用 Dictionary<string,string> 来存储一些选项,键是选项的名称,正如您猜测的那样,该值是相应选项的值。

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

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

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

Ami*_*gui 10

我为下一个谷歌用户提供的解决方案:

绑定值的另一种方法是使用 @onchange 选项,如下所述: https: //learn.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());
}
Run Code Online (Sandbox Code Playgroud)

在我的对象类(模板)中

public void changeValue(string template, string option, string value)
    {
        this.templatesList[template][option] = value;
    }
Run Code Online (Sandbox Code Playgroud)

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