码迷,mamicode.com
首页 > 其他好文 > 详细

bool?

时间:2014-06-28 19:15:31      阅读:327      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   get   os   

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 the
Required validation attribute. If I had used a regular bool, the value I received through model binding could be only true
or 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 attribute
to report a validation error. This is a nice example of how the MVC Framework elegantly blends C# features with HTML and
HTTP.

 

5.1下测试,如果不定义为 bool? ,如果未选择,绑定后值为false,但验证也未通过,实际接收的值为“”值。

bool?,布布扣,bubuko.com

bool?

标签:style   blog   http   color   get   os   

原文地址:http://www.cnblogs.com/dotnetmvc/p/3796913.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!