1

I would like to remove the validation of a specific property in ASP.NET Core Model for a specific action only like edit.

For Ex:

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; }
}

Here in the above template of the model, I want to remove the validation for the password property in Edit action because i don't want to update that in the particular action.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • Were my edits OK? I see you rolled them back and then forward again. – Kirk Larkin Sep 07 '19 at 21:19
  • Hey, here my question is different and particularly the question you have duplicated is for different technology. I have given the right and short answer for the question. So, Please understand my topic for the question. – Nishit Zinzuvadiya Sep 07 '19 at 21:25
  • 1
    A duplicate just means that the answer to your question is available elsewhere. I believe the second part of [this answer](https://stackoverflow.com/a/29539943/2630078) from that question is _exactly_ the code you've shown in your answer. Duplicates aren't _bad_; in this case, the duplicate also suggests other options that are valid in both ASP.NET and ASP.NET Core. – Kirk Larkin Sep 07 '19 at 21:29

1 Answers1

1

Yes Finally i got the answer after trying my efforts.

For ex:

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

        if (ModelState.IsValid)
        {
           ...

There is a method remove in ModelState that we can use to remove a specific validation as we needed for specific key.

ModelState.Remove("Password");

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

  • Please look at this approach described by [Darin Dimitrov](https://stackoverflow.com/a/5367788/3590235) which might work better for you. – user3590235 Sep 27 '19 at 20:19