简体   繁体   中英

How enable ModelState validation just for one Model in ASP.Net Core Razor Pages?

I am using ASP.Net Core Razor Pages web application. I have two Models in my code behind and want to enable ModelState validation just for one of them. Now, when I click on the submit button, it validates both of them.

My Modls:

public class Model1
    {
        [Key]
        public int Model1Id{ get; set; }
        [Display(Name = "Model1Name")]
        [Required]
        public string Model1Name{ get; set; }
    }



public class Model2
    {
        [Key]
        public int Model2Id{ get; set; }
        [Display(Name = "Model2Name")]
        [Required]
        public string Model2Name{ get; set; }
    }

in cshtml.cs file:

    [BindProperty]
    public Model1 Model1{ get; set; }
    [BindProperty]
    public Model2 Model2{ get; set; }

I am using the following code in the OnPost Method but it validates both of them, but I want to validate just Model1 for example:

  if (!ModelState.IsValid)
     {
            
           //Do something.
     }
   else
     {
           //Do something else
     }

Is there any way?

If you want to use ModelState , You need to delete the validation attributes of the models that do not need to be validated.

If you don't want to remove the validation attributes, you can wirte a Custom model validation. Here is a link: Custom validation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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