c# - 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";
}
解决方案
它们在您的(第一个)代码中没有问题(当前代码,classname
var 是错误的):
剪断没有问题并且正在为我运行,请在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";
}
}
推荐阅读
- node.js - Angular 网站路径无法正常工作
- python - 使用最小二乘法逼近点云(Python)
- mongodb - how to get slice of type struct defined inside another struct using go and mongodb
- c# - C#位图uri源UI冻结
- xamarin - 我在 iOS 中更改了我的应用程序包标识符。我现在需要创建新的配置文件吗?
- python - 在 Python 3.6+ 中实现描述符的正确方法是什么?
- php - 如何在发送到服务器端或客户端之前加密我网站上的数据?
- google-sheets - 查询 Google 电子表格中的所有工作表以将所有数据放入单个工作表中
- vb.net - 如何在vb.net的图片框中打印txt
- django - 我的Django网站中的SystemCheckError,为什么会出现这些中间件错误?