1.简单介绍
.NET 8 中的Blazor出来了一个新特性 [SupplyParameterFromForm],这个特性使Blazor页面中的属性(Property)的值可以由相对应的表单来提供。
2.代码
2.1 创建EditForm组件
这边表单用的是EditForm,同时指定了FormName
<FluentCard Style="margin: 16px 0px; padding: 16px; width: 600px; height: 900px;">
<EditForm Model="@Data" OnValidSubmit="ValidHandlerAsync" FormName="Create">
<DataAnnotationsValidator />
<ValidationSummary class="text-danger" />
<FluentTextField Label="Region: *"
Placeholder="Enter the region or country name"
Required
@bind-Value="@Data.Region" />
</EditForm>
</FluentCard>
2.2 添加属性
在特定的Property上加上[SupplyParameterFromForm],这样表单中的字段就会绑定到模型Data中的对应属性。
[SupplyParameterFromForm]
private CountryData Data { get; set; } = new();
也可以给特性[SupplyParameterFromForm]指定FormName属性
[SupplyParameterFromForm(FormName ="Create")]
private CountryData Data { get; set; } = new();
note, FormName要和前面EditForm的 FormName对应,这样有多个表单的场景也能适用
3.运行一下
3.1 EditForm表单
运行程序,假定有个表单如下(增加一条奥运会的奖牌记录),在表单中输入一些值
发现表单中的值能够绑定到对应的Blazor页面 Data属性中。
点击按钮 Add Olympics Data, 记录也能够保存到数据库中。
4.总结
本文简单尝试了一下Blazor的新特性[SupplyParameterFromForm],[SupplyParameterFromForm]是在.NET8中推出的,同时.NET8 也发布了很多别的新特性,这些新特性为Blazor使用者提供了便利。当前使用Blazor的人数也在逐步增加中,同时社区开源的框架也丰富了很多,感觉变化挺大的
如果哪里有错误,麻烦告之,谢谢谢谢