首页 > 解决方案 > Razor - Weird issue with updating class attribute in a foreach loop

问题描述

RESOLVED

The code I have is completely correct. The problem was that I was referencing a bootstrap.js which was interfering with the CSS. Because my actual code has bootstrap CSS, the script side of bootstrap was messing things up. It was one of the hardest bugs to find! The fix was to remove the bootstrap.js script reference.

I have an array of objects which represents a list of clickable items. In my razor page i iterate thru this array with a @foreach. Inside the loop i am rendering simple html anchor element which is clickable.

When the link is clicked an icon is to be changed (for a toggle effect). I achieve this by changing the class attribute via following way:

Item @item.Name

The issue is that when i click on one link, all other links are getting the same icon rendered. Naturally i thought this was a simple error in the code. But I can see, by using System.Console.WriteLines, that the class names that SHOULD BE APPLIED to each anchor element is CORRECT.

To paraphrase, the class names that should be applied to each anchor looks correct (based on Console outputs). But the actual class name that is rendered is not correct (based on inspecting the DOM).

Now i've looked into loop related issues in Razor/Blazor. So i am aware of the pitfalls there. This is not that kind of problem since i am iterating thru a collection of object references.

Here is a snippet of the code in question:

@foreach (var item in this.MenuItems)
{          
   var classname = item.Class == "collapsed" ? "nav collapsed" : "nav";

   <li>
       <a class="@classname" @onclick="@(() => this.ToggleItemClass(item))">@item.Name</a>
   </li>
}

// Toggle method
void ToggleItemClass(Item item)
{
   item.Class = (item.Class == "collapse") ? "collapse show" : "collapse";
}

标签: c#asp.net-coreblazor

解决方案


它们在您的(第一个)代码中没有问题(当前代码,classnamevar 是错误的):

在此处输入图像描述

剪断没有问题并且正在为我运行,请在blazorfiddle尝试。

@page "/"

<h1>Hello, world!</h1>

@foreach (var item in this.MenuItems)
{          

<li>
    <a class="@item.Class" 
       @onclick="@(() => this.ToggleItemClass(item))">@item.Name @item.Class
    </a>
</li>
}

@code {

    public class Item
    {
        public string Class {set; get;} = "blue";
        public string Name {set; get;} = "Item";
    }
    public List<Item> MenuItems = new List<Item>()
    {
        new Item(),
        new Item(),
        new Item(),
    };
    // Toggle method
    void ToggleItemClass(Item item)
    {
        item.Class = item.Class == "red" ? "green" : "red";
    }
}

推荐阅读