Issue
This Content is from Stack Overflow. Question asked by Eric
I have this on my razor page:
@foreach (AanmeldingItem ai in Aanmeldingen.Aanmeldingen)
{
<NieuweAanmeldingScherm Aanmelding=@ai SL=@SL />
}
The component “NieuweAanmeldingScherm” has a bunch of divs and inputtexts to gather some data.
On the same page as the above foreach I have a button to add a new item.
When I click this button it adds a new “AanmeldingItem” to “Aanmeldingen.Aanmeldingen” which is a list of “AanmeldingItem”.
My problem is that when I enter some data it is not updated to the item in the list.
How does this work in Blazor (I’m just starting with it)?
so basically:
@foreach (MyClass myclass in MyClasses)
{
<MyComponent Myclass=@myclass />
}
MyComponent:
<InputText @bind-value=@myclass.item1 />
<InputText @bind-value=@myclass.item2 />
@code
{
[parameter]
public MyClass myclass {get;set;}
}
How doe I make it so that MyClasses is updated with the info from the inputtexts?
Solution
Your loop is missing a @key
directive, which gives Blazor a way to identify each instance of the component when rendering.
@foreach (AanmeldingItem ai in Aanmeldingen.Aanmeldingen)
{
<NieuweAanmeldingScherm @key=ai Aanmelding=@ai SL=@SL />
}
Here, I have used the AanmeldingItem
instance as the key, but if that class has a suitable unique int,string
or some other simple type, use that instead as it will be better for performance.
This Question was asked in StackOverflow by Eric and Answered by Mister Magoo It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.