将EditForm绑定到数组时如何使EditContext.Validate()工作 [英] How to get EditContext.Validate() to work when binding EditForm to an array

查看:47
本文介绍了将EditForm绑定到数组时如何使EditContext.Validate()工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 EditForm ,它包装了一个表格,如下所示:

I created an EditForm wrapping a table like so:

**Index.razor**


@using System.ComponentModel.DataAnnotations;

<EditForm @ref="Form" Model="vms" OnSubmit="Submit">
    <DataAnnotationsValidator></DataAnnotationsValidator>
    <table class="table">
        <thead>
            <tr>
                <th>Code</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var vm in vms)
            {
                <tr>
                    <td>
                        <InputText @bind-Value="vm.Code"></InputText>
                        <ValidationMessage For="@(() => vm.Code)"></ValidationMessage>
                    </td>
                </tr>
            }
        </tbody>
    </table>
    <input type="submit" class="btn btn-primary" value="Submit" />
</EditForm>

@code{
    List<MyClass> vms;
    EditForm Form;
    class MyClass
    {
        [Required(ErrorMessage ="Required")]
        public string Code { get; set; }
    }
    protected override void OnInitialized()
    {
        vms = new List<MyClass>()
    {
            new MyClass()
            {
                Code = "1111"
            },
            new MyClass()
            {
                Code = "2222"
            }
        };
    }
    private void Submit()
    {
        bool IsValid = Form.EditContext.Validate();
    }
}

按照以下图片正确弹出消息错误:

The message error pops correctly as per the below image:

但是,当我提交表单然后进行验证时,它似乎没有收到无效状态.

However, when I submit the form and then validate, it does not seem to pick up the invalid state.

即使有错误,在调用 EditContext.Validate()后,它仍然返回true.

It is still returning true after calling EditContext.Validate(), even though there are errors.

如何使它正常工作?(当EditForm上下文中的至少一个模型项无效时,如何获得假值,以便我可以做其他验证工作?)

How do I get this to work? (How do I get false when at least one of the model item in the EditForm context is invalid so I can do my other validation stuff?)

[2021-01-16更新]答案也可以在这里找到. https://www.pragimtech.com/blog/blazor/validating-complex-models-in-blazor/

[Updated 2021-01-16] Answers can also be found here. https://www.pragimtech.com/blog/blazor/validating-complex-models-in-blazor/

简而言之,内置的DataAnnotationValidation不适用于数组.要使其正常工作,您必须

In short, the built-in DataAnnotationValidation does not work with arrays. To get it working, you must

  1. installMicrosoft.AspNetCore.Components.DataAnnotations.Validation
  2. 为数组赋予属性,然后使用[ValidateComplexType]装饰它
  3. 使用ObjectGraphDataAnnotationsValidator

推荐答案

首先,我建议您做这样的事情

First off, I'd suggest you do something like this

<EditForm EditContext="editContext" OnSubmit="Submit">

代替

<EditForm @ref="Form" Model="vms" OnSubmit="Submit">

要求您这样定义EditContext: EditContext editContext;

Which requires you to define EditContext like this: EditContext editContext;

并在OnInitialized方法中实例化EditContext对象,如下所示:

And instantiate the EditContext object in the OnInitialized method like this:

protected override void OnInitialized()
    {
        vms = new List<MyClass>() { new MyClass() { Code = "1111" },
                                    new MyClass() { Code = "2222" }
                                  };

        editContext = new EditContext(vms);
    }

偶然地,为什么您使用 OnSubmit 而不是 OnValidSubmit OnInvalidSubmit ?您在寻找挑战吗?

Incidentally, why do you use OnSubmit instead of OnValidSubmit and OnInvalidSubmit ? Are you looking for challenges ?

EditContext.Validate()返回不正确的结果

EditContext.Validate() returns incorrect results

那不是真的...

问题是您尝试绑定到MyClass数组...但是您应该绑定到单个对象.绑定到数组是可能的,但是由于它值得一个新的问题,因此我无法对其进行扩展.可以说,您可以绑定到的对象数组本身必须是单个有界对象的字段(属性),例如,一个Student对象,其中包含他所讲的语言列表.

The issue is that you try to bind to an array of MyClass...But you should bind to a single object. Binding to an array is possible, but I can't extend on it as it merits a new question. Suffice it to say that the array of objects you can bind to must be itself a field (property) of an a single bounded object, as for instance, a Student object that contains a list of Languages he speaks.

为了验证以上内容,请更改 List< MyClass>vms;

In order to verify the above, change List<MyClass> vms;

进入 MyClass模型= new MyClass();

editContext =新的EditContext(vms);

进入 editContext = new EditContext(model);

而不是

 @foreach (var vm in vms)
  {
            <tr>
                <td>
                    <InputText @bind-Value="vm.Code"></InputText>
                    <ValidationMessage For="@(() => vm.Code)"> 
       </ValidationMessage>
                </td>
            </tr>
  }

对此进行编码:

<tr>
     <td>
        <InputText @bind-Value="model.Code"></InputText>
        <ValidationMessage For="@(() => model.Code)"></ValidationMessage>
     </td>
 </tr>

现在,运行您的代码,并验证对 EditContext.Validate()的诽谤是否合理.

Now, run your code, and verify whether the defamation of the EditContext.Validate() was justified.

下面的代码示例描述如何绑定到EditForm中的集合,以及如何验证此集合以及该集合是字段成员的模型中的其他字段.

The following code sample describes how to bind to a collection in an EditForm, and how to validate this collection as well as other fields in a model of which this collection is a field member.

注意:您应该在程序包管理器控制台中执行 Install-Package Microsoft.AspNetCore.Components.DataAnnotations.Validation -Version 3.2.0-rc1.20223.4 ,以访问使示例工作所需的对象...

Note: You should execute Install-Package Microsoft.AspNetCore.Components.DataAnnotations.Validation -Version 3.2.0-rc1.20223.4 in your Package ManagerConsole, to access objects necessary to make the sample work...

@page "/"
@using Microsoft.AspNetCore.Components.Forms
@using System.ComponentModel.DataAnnotations;

<EditForm EditContext="EditContext" OnSubmit="@OnSubmitHandler">
    @*<DataAnnotationsValidator />*@
    <ObjectGraphDataAnnotationsValidator/>
    <p>
        <label for="name">Enter name: </label>
        <InputText id="name" @bind-Value="customer.Name" /><br />
        <ValidationMessage For="@(() => customer.Name)" />
    </p>
    @foreach (var phone in customer.phones)
    {
<p>
    <label>Enter phone: </label>
    <InputText @bind-Value="phone.PhoneNumber" />
    <ValidationMessage For="@(() => phone.PhoneNumber)" />
</p>
    }

    <p>
        <button type="submit">submit</button>
    </p>

</EditForm>

<div>
    <p>Edit  customer</p>

    <p>@customer.Name</p>
    @foreach (var phone in customer.phones)
    {
        <p>@phone.PhoneNumber</p>

    }

</div>
<div>
     <p>Is model validated: @validated.ToString()</p>
 </div>
@code {
    EditContext EditContext;
    Customer customer;
    bool validated;

    protected override void OnInitialized()
    {
        customer = new Customer();
        EditContext = new EditContext(customer);

    }
    private void OnSubmitHandler()
    {            
        validated = EditContext.Validate();
    }

    public class Customer
    {
        [Required]
        public string Name { get; set; }  
        [ValidateComplexType]
        public List<Phone> phones { get; set; } = new List<Phone>() { new Phone { }, new Phone { }, new Phone { }};
         
    }

    public class Phone
    {
        [Required]
        public string PhoneNumber { get; set; }
    }

}

这篇关于将EditForm绑定到数组时如何使EditContext.Validate()工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆