What is the best way to bind dynamics values in blazor

Viewed 2382

I am using a Dictionary<string,string> to store some options, the key is the name of the option and as you guess the value is the value of the correspendent option.

in my razor file i have this bit of code :

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

And what i'm searching to do is to store the value of the text input into the right value in my Dictionary, sadly we can not use @bind = @option.Value.

1 Answers

My solution for the next googlers:

An alternative way to bind a value is to use @onchange option like described here : https://docs.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-3.1

So, i changed the code as follow :

in the razor file :

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

And in My object class (Template)

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

I don't know if it's the cleanest thing to do it this way or not, but it does the job perfectly.

Related