英文:
EditForm Validate with Multiple Classes
问题
我有一个包含多个类的剃刀EditForm页面,每个类都有自己的数据注释。当提交这个表单时,必须将数据插入不同的表格。当我点击提交时,没有触发任何验证。
<EditForm Model="@ViewModel.EditModel" OnSubmit="OnSubmit">
private void OnSubmit(EditContext context)
{
context.EnableDataAnnotationsValidation(); // 尝试强制执行验证
if (context.Validate()) // 总是为真
{
// 做一些操作
}
}
至于ViewModel,它有一个名为InformationSave的类,其中包含5个不同的类。
InformationSave EditModel { get; set; }
如果InformationSave.cs包含以下内容:
public TableA tablea { get; set; } = new TableA();
public TableB tablea { get; set; } = new TableB();
public TableC tablea { get; set; } = new TableC();
public TableD tablea { get; set; } = new TableD();
public TableE tablea { get; set; } = new TableE();
如果只有一个类(例如TableA)进行验证,那么验证会触发,但如果有多个类,则验证不会触发。
英文:
I have a razor EditForm page that it's model has several classes on it, each class has it's own data annotations. This form when submit must insert data to different tables. When I click the submit no validations are triggered.
<EditForm Model="@ViewModel.EditModel" OnSubmit="OnSubmit">
private void OnSubmit(EditContext context)
{
context.EnableDataAnnotationsValidation(); //Trying to force the validations
if(context.Validate()) //Always true
{
//Do stuff
}
}
As for the ViewModel it has a class named InformationSave that holds 5 different classes.
InformationSave EditModel { get; set; }
if the InformationSave.cs having
public TableA tablea { get; set; } = new TableA();
public TableB tablea { get; set; } = new TableB();
public TableC tablea { get; set; } = new TableC();
public TableD tablea { get; set; } = new TableD();
public TableE tablea { get; set; } = new TableE();
If I have a single class validation, for example, only TableA, then the validations do trigger, but not having multiple classes.
答案1
得分: 1
你需要添加 NuGet 包 Microsoft.AspNetCore.Components.DataAnnotations.Validation (请记住这是预发布版!)。然后在你的 Razor 文件中,不要使用 <DataAnnotationsValidator/>
,而要使用 <ObjectGraphDataAnnotationsValidator/>
。最后,你需要像这样修饰你的子类:
[ValidateComplexType]
public TableA tablea { get; set; } = new TableA();
[ValidateComplexType]
public TableB tablea { get; set; } = new TableB();
希望这对你有所帮助。
英文:
You need to add the nuget package
Microsoft.AspNetCore.Components.DataAnnotations.Validation
(it's prerelease, keep that in mind!)
Then in your razor file instead of <DataAnnotationsValidator/>
you will use <ObjectGraphDataAnnotationsValidator/>
.
Finally, you will decorate your child classes like this:
[ValidateComplexType]
public TableA tablea { get; set; } = new TableA();
[ValidateComplexType]
public TableB tablea { get; set; } = new TableB();
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论