使用 Razor Pages 7 时,我在代码隐藏文件中包含以下内容:
public record PersonDto(
long Id,
string Name,
[BindNever] string Address,
// ...
);
[BindProperty] public PersonDto Person { get; set; }
我将其填充在
OnGet()
中并将其显示在页面上。我在OnPost()
中阅读它来更新数据库。
但是
Address
应该是只读的。我不允许更改它,因此后处理程序总是失败并出现验证错误 "The Address field is required"
。
BindNever
属性对记录不起作用(尽管文档表明它应该起作用)。我也尝试了长格式记录语法,结果相同。
有人知道为什么吗?
我找到了一个解决方法。我替换了这个:
[BindNever] string Address,
这样:
string? Address,
BindNeverBindNeverAttribute
类用于属性:
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Parameter | System.AttributeTargets.Property,AllowMultiple = false,Inherited = true)]
公共密封类 BindNeverAttribute { ... }
但是您在 Field 上应用了该属性。
我希望将其更改为
[BindNever] string Address { get; set; }
可以解决您的问题。
据我所知,.NET 中的所有模型绑定都需要属性而不是字段。