In my table, I have a List op type Person
called PersonList
. When a row is clicked, another object (Model) of type Person
, is set to that value of that row, so my EditForm
gets updated with that value. So far so good.
But when I change te value in my EditForm
, my List get also updated with that value.
How is that possible? And how to prevet it?
Many thanks!
<h3>Component</h3>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
@foreach (var person in PersonList)
{
<tr @onclick="@(() => ActivateItem(person))">
<td>@person.Id</td>
<td>@person.Name</td>
<td>@person.Age</td>
</tr>
}
</tbody>
</table>
<EditForm Model="Model">
<InputText @bind-Value="Model.Name" />
<InputNumber @bind-Value="Model.Age" />
</EditForm>
@code {
private List<Person> PersonList = new List<Person>();
private Person Model = new Person();
private void ActivateItem(Person person)
{
Model = person;
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
protected override void OnInitialized()
{
PersonList.Add(new Person
{
Id = 1,
Name = "Jack",
Age = 20
});
PersonList.Add(new Person
{
Id = 2,
Name = "Paul",
Age = 25
});
PersonList.Add(new Person
{
Id = 3,
Name = "Brad",
Age = 30
});
}
}
Well, it is because you are keeping the reference to the object and bind-value is a two way binding. Not strange at all.
One solution is to use a one way binding and the other solution would be to remove the reference from the object by instansiate a new object. Something like this:
private void ActivateItem(Person person)
{
Model = new Person
{
Id = person.Id,
Name = person.Name,
Age = person.Age
};
}