What is the best way to bind dynamics values in blazor
Asked Answered
A

1

8

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.

Agrimony answered 1/7, 2020 at 14:35 Comment(4)
Why can't you use @bind = option.ValueKowal
It seems that the value is read only type, you can't modify it, at least not in the razor fileAgrimony
Try to bind to templates.templatesList[SelectionValue][option.Key]Mcginty
@Mcginty Keys and Values are readonly, so it's hard to outmaneuver this outside the object class, i pruposed a temporary solution that works fine.Agrimony
A
10

My solution for the next googlers:

An alternative way to bind a value is to use @onchange option like described here : https://learn.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.

Agrimony answered 8/7, 2020 at 15:5 Comment(1)
And how do you reset values ?Charades

© 2022 - 2024 — McMap. All rights reserved.