liveBook · Manning

Nullable Boolean

As explained in Pro ASP.NET Core 7, Tenth Edition

A nullable Boolean is a Boolean value type that can represent true, false, or null.

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

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains three-state behavior and its interaction with Required validation and model binding, but not nullable-type internals.
Examples
Uses an RSVP GuestResponse model and a WillAttend form choice with an empty option.
What you can do after
Apply it via ASP.NET Core model binding to validate whether users answered a Boolean form question.
How it connects
Connects nullable types with HTML forms, HTTP, model binding, validation attributes, and ModelState.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.