【问题标题】:Can I remove the validation of specific property of model in specific actions? [duplicate]我可以在特定操作中删除对模型特定属性的验证吗? [复制]
【发布时间】:2019-09-07 20:27:20
【问题描述】:

我想在 ASP.NET Core 模型中删除对特定属性的验证,仅用于编辑等特定操作。

例如:

public class User {
    [Key]
    public Guid User_ID { get; set; } 

    [Required]
    [Display(Name = "Username")]
    public string User_name { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }        

    [DataType(DataType.PhoneNumber)]
    public string Mobile_No { get; set; }
}

在上面的模型模板中,我想删除 编辑操作 中密码属性的验证,因为我不想在特定操作中更新它。

【问题讨论】:

  • 我的编辑是否正常?我看到您将它们向后滚动,然后再次向前滚动。
  • 嘿,我的问题是不同的,特别是你重复的问题是针对不同的技术。我已经对这个问题给出了正确而简短的答案。所以,请理解我的问题。
  • 重复只是意味着您的问题的答案在其他地方可用。我相信该问题中this answer 的第二部分正是您在答案中显示的代码。重复不是;在这种情况下,副本还建议在 ASP.NET 和 ASP.NET Core 中都有效的其他选项。

标签: c# asp.net-core


【解决方案1】:

是的,经过努力我终于得到了答案。

例如:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(Guid id,Users users)
    {
        if (id != users.User_ID)
        {
            return NotFound();
        }
        ModelState.Remove("Password");

        if (ModelState.IsValid)
        {
           ...

ModelState 中有一个方法 remove ,我们可以使用它来删除我们需要特定键的特定验证。

ModelState.Remove("密码");

参考: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.modelstatedictionary.remove?view=aspnetcore-2.2

【讨论】:

  • 请查看Darin Dimitrov 描述的这种方法,它可能更适合您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 2023-04-04
  • 2021-03-15
  • 1970-01-01
  • 2016-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多