编辑表单使用多个类进行验证

huangapple go评论68阅读模式
英文:

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.

&lt;EditForm Model=&quot;@ViewModel.EditModel&quot; OnSubmit=&quot;OnSubmit&quot;&gt;

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 &lt;DataAnnotationsValidator/&gt; you will use &lt;ObjectGraphDataAnnotationsValidator/&gt;.

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();

...

huangapple
  • 本文由 发表于 2023年6月19日 07:25:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定