【问题标题】:ModelState.Isvalid, why does it validate relatetd Tabels?ModelState.Isvalid,为什么要验证相关的表?
【发布时间】:2021-03-19 22:54:56
【问题描述】:

这是要验证的属性。 (来自我的 cshtml.cs(Razor)的代码)

    [BindProperty]
    public TMedProductStorageLocation TMedProductStorageLocation { get; set; }
    [BindProperty]
    public IList<TStorageLocation> TStorageLocations { get; set; }
    [BindProperty]
    public int SelectedStorageLocationId { get; set; }
    [BindProperty]
    public TMedProduct SelectedProduct { get; set; }

    [BindProperty]
    public int RelocateAmount { get; set; }

这些是我要验证的属性。但它也验证了:

  public class TSubstanceGroup
{

    public TSubstanceGroup()

    {
        TMedProducts = new HashSet<TMedProduct>();

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

    [Required(ErrorMessage = "Geben Sie eine Bezeichnung ein.")]

    public string Name { get; set; }

    public ICollection<TMedProduct> TMedProducts { get; set; }
}

因为这是与 TMedProduct 相关的表。 如何避免对相关表进行验证?

【问题讨论】:

  • 您能分享一下您的剃须刀页面前端吗?

标签: validation asp.net-core entity-framework-core razor-pages entities


【解决方案1】:

不确定你的 razor pages 设计是什么,但你需要知道 ModelState 会验证你在 razor pages 后端定义的所有模型,而不是因为你在模型之间有关系:

public class PrivacyModel : PageModel
{
    [BindProperty]
    public TSubstanceGroup TSubstanceGroup { get; set; }
    [BindProperty]
    public TMedProduct SelectedProduct { get; set; }
    [BindProperty]
    public TMedProductStorageLocation TMedProductStorageLocation { get; set; }
    [BindProperty]
    public IList<TStorageLocation> TStorageLocations { get; set; }
    [BindProperty]
    public int SelectedStorageLocationId { get; set; }
    [BindProperty]
    public int RelocateAmount { get; set; }
    public IActionResult OnPost()
    {
       //...
    }

    public void OnGet()
    {
        //..
    }
    
}

为避免对相关表进行验证,您可以使用密钥删除验证:

public IActionResult OnPost()
{
    ModelState.Remove("KeyName");
    if(ModelState.IsValid)
    {
        //...
    }
    return Page();
}

关于如何知道键名,你可以查看ModelState:

【讨论】:

  • 嘿,谢谢你的回答!!现在我知道为什么 Modelstate 无效以及如何避免它。
猜你喜欢
  • 2010-12-19
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2012-05-20
相关资源
最近更新 更多