4. Models
A model represents the data your application works with. It is a normal C# class with properties. Models can also carry validation rules using data annotations. A view model is a model made only for one view, holding exactly the fields that view needs.
Key points
- Keep models simple: properties, plus validation attributes.
- Use a view model when a page needs data from several models or only a few fields.
- Never send database entities that contain private fields (like passwords) straight to a view.
Example: A model with validation
using System.ComponentModel.DataAnnotations;
public class Student
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(50)]
public string Name { get; set; }
[Range(16, 100)]
public int Age { get; set; }
[EmailAddress]
public string Email { get; set; }
}
Show explanation
Each attribute is a rule. If a user submits an empty Name or an age of 5, validation fails and an error message can be shown on the form.
Example: A view model
public class StudentListViewModel
{
public List<Student> Students { get; set; } = new();
public string SearchText { get; set; }
public int TotalCount { get; set; }
}
Show explanation
This class exists only to give one page everything it needs in a single object.