.NET 8 Blazor新托管模式下EditForm绑定模型属性为空问题排查
问题分析:Blazor EditForm 模型绑定为空的原因
问题描述
在.NET 8 Blazor新托管模式下开发Web应用,将Product模型绑定到EditForm组件,在OnInitializedAsync()中初始化模型。提交表单时,UI输入框已填写内容,但绑定的productModel对象属性始终为空,预期表单数据能正确绑定到模型。
代码示例
@page "/insertProduct" @using DbContext DB @using System.ComponentModel.DataAnnotations <h3>Insert New Product</h3> <EditForm Model="@productModel" OnValidSubmit="@HandleValidSubmit"> <DataAnnotationsValidator /> <ValidationSummary /> <div class="form-group"> <label for="name">Product Name</label> <InputText id="name" class="form-control" @bind-Value="productModel.Name" /> </div> <div class="form-group"> <label for="description">Description</label> <InputTextArea id="description" class="form-control" @bind-Value="productModel.Description" /> </div> <div class="form-group"> <label for="price">Price</label> <InputNumber id="price" class="form-control" @bind-Value="productModel.Price" /> </div> <div class="form-group"> <label for="stock">Stock</label> <InputNumber id="stock" class="form-control" @bind-Value="productModel.Stock" /> </div> <button type="submit" class="btn btn-primary">Submit</button> </EditForm> @if (isSubmitted) { <div class="alert alert-success" role="alert"> submitted! </div> } @code { [SupplyParameterFromForm] private Product productModel {get;set;} private bool isSubmitted = false; protected override async Task OnInitializedAsync() { productModel = new Product(); } private async Task HandleValidSubmit() { isSubmitted = true; DB.Products(productModel); // product is empty here await DB.SaveChangesAsync(); productModel = new Product(); } }
核心原因及解决方案
1. [SupplyParameterFromForm] 属性误用
在.NET 8 Blazor新托管模式中,[SupplyParameterFromForm]用于自动从表单请求体绑定参数到组件属性,但它的执行时机早于OnInitializedAsync:
- 框架先尝试通过表单数据填充
productModel - 随后
OnInitializedAsync将productModel重新赋值为空的Product实例,直接覆盖了表单绑定的数据 - 最终提交时
productModel为空对象
解决:移除[SupplyParameterFromForm]属性,EditForm的双向绑定无需该属性,组件会自动管理模型状态更新。
2. 模型属性可绑定性检查
确保Product类的属性是公共可读写的,必要时添加数据注解(如[Required])以支持验证。如果属性为只读或私有,Blazor无法完成双向绑定。
示例正确的Product类:
public class Product { public int Id { get; set; } [Required] public string Name { get; set; } public string Description { get; set; } [Range(0.01, double.MaxValue)] public decimal Price { get; set; } [Range(0, int.MaxValue)] public int Stock { get; set; } }
3. 数据上下文操作错误
代码中DB.Products(productModel)的写法有误,正确添加实体的方式应为DB.Products.Add(productModel),否则实体不会被上下文跟踪,保存操作无效。
修正后的代码片段
@code { // 移除[SupplyParameterFromForm] private Product productModel {get;set;} private bool isSubmitted = false; protected override void OnInitialized() { productModel = new Product(); } private async Task HandleValidSubmit() { isSubmitted = true; DB.Products.Add(productModel); // 修正实体添加逻辑 await DB.SaveChangesAsync(); productModel = new Product(); } }
内容的提问来源于stack exchange,提问作者Aw Azeem
相关产品推荐
相关产品推荐

