我正试图将用户列表传递给我正在开发的自定义组件,但我收到了构建错误:
当前上下文中不存在名称"users"。
代码:
@page "/transactions/list"
@using Accounting.Web.Components.DataTable;
<h3>List</h3>
List
<DataTable Items="users" class="table table-bordered">
</DataTable>
@code {
public class User
{
public int Id { get; set; }
public string Username { get; set; }
}
public List<User> users { get; set; } = new();
User user = new()
{
Id = 1,
Username = "Me"
};
users.Add(user); @<< This is where the error occurs
}
我看不出哪里出了问题。。。
语句不能存在于方法之外。
示例
@code {
public class User
{
public int Id { get; set; }
public string Username { get; set; }
}
public List<User> users { get; set; } = new();
User user = new()
{
Id = 1,
Username = "Me"
};
// executed when the component is initialized
// You can use this method to load data
protected override void OnInitialized()
{
users.Add(user);
}
}
指令需要封装在方法中。如果要在组件中加载数据,可以覆盖OnInitialized
:
@code {
public class User
{
public int Id { get; set; }
public string Username { get; set; }
}
public List<User> users { get; set; } = new();
User user = new()
{
Id = 1,
Username = "Me"
};
protected override void OnInitialized()
{
users.Add(user);
}
}
但我认为你只需要数据来测试显示器。在这种情况下,您可以简化为:
@code {
public class User
{
public int Id { get; set; }
public string Username { get; set; }
}
public List<User> users { get; set; } = new List<User>{
new User{
Id = 1,
Username = "Me"
},
new User{
Id = 2,
Username = "You"
}
};
}