Aztec Consulting
Aztec Consulting

Reputation: 23

Razor Generic List won't add new items

In the code example below, I have added to the logic in the increment counter demo to display the contents of a list, and then in the on click event to add a "New Item" to the list. However, try as I might the add doesn't add... The two Console.WriteLine dutifully show the list with three members before and after the add, but there are not errors reported and nothing changes with the list.

Example code:

@page "/ListIncrement"

<div>
    <p>Current count: @currentCount</p>

    <ul>
        @foreach (var ListItem in TestList)
        {
            <li>@ListItem</li>
        }
    </ul>

    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

</div>

@code {
    private int currentCount = 0;

    public List<string> TestList => new List<string>{
        "one", "Two", "Three" };

    private void IncrementCount()
    {
        currentCount++;

        Console.WriteLine("Count= {0}", TestList.Count);
        TestList.Add("New Item");
        Console.WriteLine("Count= {0}", TestList.Count);

    }
}

Upvotes: 0

Views: 62

Answers (1)

Kyle
Kyle

Reputation: 33731

The problem is with this line

 public List<string> TestList => new List<string>{ "one", "Two", "Three" };

Change it to this and it will work:

 public List<string> TestList = new List<string>{ "one", "Two", "Three" };

The => arrow is called an Expression-bodied-member and it runs the expression whenever TestList is called, so when the component goes to get TestList, it ends up returning a new List<string>{ "one", "Two", "Three" }; each time, instead of only creating the new list at initialization.

Here's some more information: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

Upvotes: 5

Related Questions