带有表单验证的System.InvalidOperationException

时间:2019-09-14 12:32:56

标签: c# blazor

我当前正在运行.net core 3的预览版9。我正在尝试使表单验证生效。我正在从forms and validation

复制示例

型号

namespace BlazorListPreview9.Model
{
    public class ItemModel
    {
        [Required]
        [StringLength(10, ErrorMessage = "Name is too long.")]
        public string Name { get; set; }
    }
}

表格

@page "/FormsValidation"
@using BlazorListPreview9.Model;

<EditForm Model="@itemModel" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText id="name" @bind-Value="@itemModel.Name" />
    <button type="submit">Submit</button>
</EditForm>

@code {
    private ItemModel itemModel = new ItemModel();

    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}

错误

  

WASM:System.InvalidOperationException:类型为“ BlazorListPreview9.Components.EditForm”的对象没有与名称“ Model”匹配的属性。

1 个答案:

答案 0 :(得分:0)

'BlazorListPreview9.Components'中是否有一个名为EditForm的类定义?我认为不是吧?

我觉得这与安装,软件包参考等有关。

请尝试以下代码并报告其是否有效: 请注意,除了提供Model之外,还可以提供EditContext对象。最终结果是相同的...

@page "/FormsValidation"
@using BlazorListPreview9.Model;

<EditForm EditContext="@editContext" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText id="name" @bind-Value="@itemModel.Name" />
    <button type="submit">Submit</button>
</EditForm>

@code {
    private EditContext editContext;

    private ItemModel itemModel = new ItemModel();

     protected override void OnInitialized()
  {
    this.editContext = new EditContext(itemModel );
   }
    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}

希望这对您有帮助...