bool?

3069 ワード

public class GuestResponse

    {

        [Required(ErrorMessage = "Please enter your name")]

        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter your email address")]

        [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please enter a valid email address")]

        public string Email { get; set; }

        [Required(ErrorMessage = "Please enter your phone number")]

        public string Phone { get; set; }

        [Required(ErrorMessage = "Please specify whether you'll attend")]

        public bool? WillAttend { get; set; }

    }

Tip As noted earlier, I used a nullable bool for the WillAttend property. I did this so that I could apply theRequired validation attribute. If I had used a regular bool, the value I received through model binding could be only trueor false, and I wouldn’t be able to tell if the user had selected a value. A nullable bool has three possible values: true,false, and null. The null value will be used if the user hasn’t selected a value, and this causes the Required attributeto report a validation error. This is a nice example of how the MVC Framework elegantly blends C# features with HTML andHTTP.
 
5.1 boolとして定義されていない場合は、テストを行います.選択されていない場合、バインド後の値はfalseですが、検証も通過せず、実際に受信した値は「」値です.