I have one model class like:
public class Student { [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] [Display(Name = "Enrollment Date")] public DateTime EnrollmentDate { get; set; } [Required] [Display(Name = "Is Active")] public bool IsActive { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } }
Here I have created a Boolean
property IsActive
with Required
attribute, but the problem is that my view is not executing the required validation for this property? I want to bind this property with a CheckBox
and check if this CheckBox
is checked and run validation if it is not.
Any solution for this?
The Required attribute just means that the property has to have a value. In the case of boolean (checkbox) the value false (or unchecked) is still a valid answer. I knew this fact that it is not working because unchecked is also a valid value for Boolean property, that's why I am looking for a solution to this.
Required Attribute in ASP.NET MVC: let’s understand Required Attribute with one example. Our business requirement is that the First name and Last Name of an employee can’t be empty. That means we will force the Employee to give the first name and last name; we can achieve this very easily in ASP.NET MVC application by decorating the ...
Let’s create the Model class as follows, Once creating the new MVC Project Solution, right-click on the Model folder and add a new class Addà Class as shown below, Once adding the new class, give the proper name to the Model and click add. To create the model, this corresponds to the database table,
So let’s discuss the built-in Data Annotation Attributes that are available in ASP.NET MVC for model validation one by one. Note: Data annotations are the attributes that we can find in the System.ComponentModel.DataAnnotations namespace. These attributes provide Server-side validation as well as client-side validation.
[Display(Name = "Is Active")] [Range(typeof(bool), "true", "true", ErrorMessage="The field Is Active must be checked.")] public bool IsActive { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With