简体   繁体   English

禁用对 ASP.Net Core 中特定输入的验证

[英]Disable validation for specific inputs in ASP .Net Core

I am facing an issue when validating a form on ASP.在 ASP 上验证表单时遇到问题。

I have 2 models Person and Address.我有 2 个模型 Person 和 Address。 Each of them have their specific forms to add entries using EF Core.他们每个人都有自己特定的 forms 以使用 EF Core 添加条目。

In Person form I need hidden inputs to keep track of potential Address related data (It is perfectly fine there is no Address).在 Person 表单中,我需要隐藏输入来跟踪潜在的 Address 相关数据(没有 Address 也很好)。 To that matter I use hidden input fields but because the Address model have validation annotations, the generated markup reflects it which puts ModelState.IsValid to false upon validation unless, of course, I am editing a person with valid Address data.就此而言,我使用隐藏的输入字段,但因为地址 model 具有验证注释,生成的标记反映了它,在验证时将 ModelState.IsValid 设置为 false,当然,除非我正在编辑具有有效地址数据的人。

I also tried to set Person.Address to null in the specific situation where it should be just before actually checking its value and it does not work.我还尝试在特定情况下将 Person.Address 设置为 null,它应该在实际检查其值之前设置,但它不起作用。 Probably it is already too late for ModelState to update by then.到那时 ModelState 更新可能已经太迟了。

if (Person.Address is not null && Person.Address.Id == 0)
    Person.Address = null;

if (ModelState.IsValid)
    // Further code to save data in DB
else
    // Code to redisplay the page

I would like to know if there is a way to tell ASP not to validate/ignore specific input fields but still allow me to keep a piece of data?我想知道是否有办法告诉 ASP 不要验证/忽略特定的输入字段但仍然允许我保留一段数据?

Thank you very much.非常感谢你。

Edit: As per demand in the comments I add the classes with annotation编辑:根据评论中的要求,我添加了带有注释的类

The Person此人

public class Person
{
  [Key]
  public int Id { get; set; }

  [Required]
  public string FirstName { get; set; }

  [Required]
  public string LastName { get; set; }

  [Range(0, 150)]
  public int Age { get; set; }

  public Address Address { get; set; }
}

The address class地址 class

public class Address
{
  [Key]
  public int Id { get; set; }

  [Required, MaxLength(50)]
  public string Street { get; set; }

  [Required, MaxLength(50)]
  public string City { get; set; }

  [Required, MaxLength(50)]
  public string Country { get; set; }
}

OK Problem solved. OK 问题解决了。 I found some interesting doc.我发现了一些有趣的文档。

Thanks for the propositions.感谢您的提议。

在此处输入图像描述

You can skip data annotations on those fields which you don't want to validate.您可以跳过不想验证的那些字段上的数据注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM