A nullable Boolean can represent true, false, or null. In an ASP.NET Core form model, null distinguishes an unanswered choice from an explicit true or false answer. section 3.2.9
Use a nullable Boolean when validation must detect that a Boolean choice was left unanswered:
- Declare the property as `public bool? WillAttend { get; set; }`. section 3.2.9
- Apply `[Required]`; model binding leaves the property null when the user selects no value, allowing validation to fail. section 3.2.9
- Check `ModelState.IsValid` in the POST action before accepting the response. section 3.2.9
RSVP attendance choice
An RSVP form can offer an empty option plus true and false values for `WillAttend`. An ordinary `bool` would collapse an unanswered choice into either true or false; `bool?` preserves the distinction so `[Required(ErrorMessage = "Please specify whether you'll attend")]` can report the error. section 3.2.9
Listing 3.17 Applying validation in the GuestResponse.cs file in the Models folder
using System.ComponentModel.DataAnnotations;
namespace PartyInvites.Models {
public class GuestResponse {
[Required(ErrorMessage = "Please enter your name")]
public string? Name { get; set; }
[Required(ErrorMessage = "Please enter your email address")]
[EmailAddress]
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; }
}
}
Inspect the complete GuestResponse model, including the nullable attendance property and its validation attributes. section 3.2.9
