可以在页面中直接编写C#代码(@Code{}),如:
@page "/"
<PageTitle>@UserName</PageTitle>
<div>
<Counter Messages=@outputMessages></Counter>
</div>
<button class="btn btn-primary">@UserName</button>
@code{
private string UserName = "小明";
public Dictionary<string, object> outputMessages{set;get;} =
new Dictionary<string, object>{
{"111", "111"},
{"222", "222"}
};
private void OnInput(ChangeEventArgs args)
{
var newValue = args.Value?.ToString() ?? string.Empty;
UserName = newValue.Length > 4 ? "Long!" : newValue;
}
}
也可以分开:
Index.razor
@page "/"
<PageTitle>@UserName</PageTitle>
<div>
<Counter Messages=@outputMessages></Counter>
</div>
<button class="btn btn-primary" @onclick="OnInput">@UserName</button>
Index.razor.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Components.Web;
namespace MyProject.Pages;
public partial class Index
{
private string UserName = "小明";
private void OnInput(MouseEventArgs e)
{
UserName = "Hello!";
}
}
结果:
