我正在学习Blazor。 我创建了一个具有 CustomerID 和 CustomerName 的客户类,并且能够将测试客户添加到我的客户列表中,但是当我在 Foreach 循环中使用 LIST(客户(来显示它们时,我收到错误"客户名称未出现在当前上下文中"。 请查看代码。我做错了什么?
enter code here
@page "/displaycustomers"
@using System.Collections.Generic
@using CustomerBlazorServerApp.Data
<h3>Display Customers</h3>
<table class="table">
<thead>
<tr>
<th>CustomerID</th>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
@foreach (var acustomer in thecustomers)
{
<tr>
<td>acustomer.CustomerID</td>
<td>acustomer.CustomerName</td>
</tr>
}
</tbody>
</table>
@code {
// protected virtual void OnInitialized ();
protected override void OnInitialized()
{
List<Customer2> thecustomers = new List<Customer2>();
new Customer2 { CustomerID = "123", CustomerName = "Any Company" };
new Customer2 { CustomerID = "456", CustomerName = "Some Company" };
thecustomers.Add(new Customer2 { CustomerID = "123", CustomerName = "Any Company" });
thecustomers.Add(new Customer2 { CustomerID = "456", CustomerName = "Some Company" });
}
}
这一行:
List<Customer2> thecustomers = new List<Customer2>();
需要移出OnInitialized
.当它在OnInitialized
内部声明时,它的作用域只是该函数,不能在其外部访问。
例:
@page "/"
@using System.Collections.Generic
<h3>Display Customers</h3>
<table class="table">
<thead>
<tr>
<th>CustomerID</th>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
@foreach (var acustomer in thecustomers)
{
<tr>
<td>acustomer.CustomerID</td>
<td>acustomer.CustomerName</td>
</tr>
}
</tbody>
</table>
@code {
List<Customer2> thecustomers = new List<Customer2>();
protected override void OnInitialized()
{
thecustomers.Add(new Customer2 { CustomerID = "123", CustomerName = "Any Company" });
thecustomers.Add(new Customer2 { CustomerID = "456", CustomerName = "Some Company" });
}
public class Customer2
{
public string CustomerID { get; set; }
public string CustomerName { get; set; }
}
}
如@Kyle所述,将列表移出方法。但是,您还需要告诉渲染器<td>acustomer.CustomerID</td>
是生成的内容。
TLDR:<td>@acustomer.CustomerID</td>
顺便说一句,你不需要@using System.Collections.Generic
.默认情况下,它"导入"到剃须刀组件中。还应在 _imports.razor.cs 文件中定义常用的导入。