@{
}
不能使用@{}下的function或set get属性,只能使用declare。例如:
@{
DateTime today = DateTime.Now;
}
但下面的代码会显示错误,因为我在这里使用 function:
@{
public DateTime GetDate()
{
return DateTime.Now;
}
}
@代码{
}
您可以在 @code {} 下编写任何 C# 代码,例如:
@code{
[Parameter]
public Guid id { get; set; }
AccessoryDto accessory;
protected override Task OnInitializedAsync()
{
if (id == Guid.Empty)
accessory = new AccessoryDto();
else
accessory = GetAccessory(id);
return Task.FromResult(accessory);
}
void cancel()
{
NavigationManager.NavigateTo("/accessories");
}
}
@函数{
}
@function 与 @code 做同样的事情,但现在,@code推荐使用。
除此之外,还可以使用@符号来使用条件、循环等。例如:
@if (id == null)
{
<h1>Create</h1>
}
else
{
<h1>Edit</h1>
}
和
<tbody>
@foreach (var accessory in Accessories)
{
<tr>
<td>@accessory.Name</td>
<td>@accessory.Description</td>
<td>
<a href='/editaccessory/@accessory.Id'>Edit</a> |
<a href='/delete/@accessory.Id'>Delete</a>
</td>
</tr>
}
</tbody>
此外,还可以@()进行表达。例如:
<a href="@($"employee/{employeeId}")">View</a>