liveBook · Manning

System.ComponentModel.DataAnnotations

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

The .NET namespace containing attributes and related types for describing data models and enforcing validation rules.

System.ComponentModel.DataAnnotations supplies attributes for declaring validation rules on ASP.NET Core model classes. Model binding detects those attributes and records failures in ModelState. section 3.2.9

A practical validation setup combines:

  • Required attributes with custom messages for missing names, email addresses, phone numbers, and attendance choices. section 3.2.9
  • EmailAddress on the email property to reject invalid email input. section 3.2.9
  • A nullable bool for WillAttend, allowing null to distinguish no selection from true or false. section 3.2.9
  • ModelState.IsValid in the POST action to save valid responses or redisplay the form with errors. 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 GuestResponse model with its validation attributes and custom error messages. section 3.2.9

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

How deep it goes
Explains attribute application, nullable-value behavior, ModelState checks, and validation-error rendering, but not custom validators.
Examples
Uses a GuestResponse RSVP form with Required, EmailAddress, nullable bool, validation summaries, and styled invalid fields.
What it assumes
Assumes C# model and controller basics while demonstrating validation from attribute declaration through submitted-form feedback.
What you can do after
Builds attribute-validated ASP.NET Core forms and handles invalid submissions through ModelState.
How it connects
Connects model classes, model binding, ModelState, controllers, Razor views, and HTML validation helpers.

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.