【问题标题】:how i can Show error for unique fields in asp.net core我如何在 asp.net 核心中显示唯一字段的错误
【发布时间】:2020-05-10 06:26:14
【问题描述】:

我有一个与验证属性相关的问题!我使用 .net 核心 2.1。我检查了 DbContext 类的 OnModelCreating 方法中的唯一字段,它工作正常。现在,如果用户在 Display & Required & MaxLength & ... 属性等输入字段中输入相同的 BirthCertificate 值(数据库中已经存在),我想显示一条错误消息,并将其发送(绑定)到 ModelState 进行检查.我还在客户端中使用 jquery.validate.js 并显示所有错误,它工作正常。我应该怎么做:

Public Class Person
{
   [Display(Name = "Enter BirthCertificate")]
   [Required(ErrorMessage = "Please enter {0}")]
   [MaxLength(10, ErrorMessage = "Max lenght is {0}")]
   public string BirthCertificate { get; set; }
}

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<DomainClasses.Person.Person>(entity =>
    {
        entity.HasIndex(e => e.BirthCertificate).IsUnique();  // it's working fine
    });
}

谢谢

【问题讨论】:

    标签: validation asp.net-core .net-core fluentvalidation


    【解决方案1】:

    您可以使用其中任何一种。

    1) 在 SQL Server 中为 BirthCertificate 创建新的唯一键。使用 catch (Exception ex) 并返回 ajax 显示错误。

    2) 做检查代码

    if (db.Person.Where(x => x.BirthCertificate.Contains(birthcert)).Any())
    {
         //return to ajax to show error
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-25
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      相关资源
      最近更新 更多