Models in ASP.NET Core

Models are a fundamental part of the Model-View-Controller (MVC) and Model-View-ViewModel (MVVM) architectural patterns. In ASP.NET Core, models represent the data and business logic of your application.

What are Models?

A model is typically a class that encapsulates the application's data. It can also contain logic for:

Models should be independent of the user interface (UI) and the specific way data is retrieved or displayed. They focus solely on the data itself and how it should behave.

Creating Models

You can create models in ASP.NET Core by defining simple C# classes. Here's an example of a basic product model:


namespace YourApp.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Description { get; set; }
    }
}
            

Data Annotations for Validation

ASP.NET Core provides a rich set of data annotation attributes that can be used to define validation rules directly on your model properties. These attributes are part of the System.ComponentModel.DataAnnotations namespace.

Common Validation Attributes:

Attribute Description
[Required] Specifies that a data field is required.
[StringLength(maxValue)] Validates that a string property does not exceed a specified maximum length.
[Range(minValue, maxValue)] Validates that a numeric property falls within a specified range.
[EmailAddress] Validates that a string property is a valid email address format.
[Url] Validates that a string property is a valid URL format.
[RegularExpression(pattern)] Validates that a string property matches a specified regular expression.

Example with Data Annotations:


using System.ComponentModel.DataAnnotations;

namespace YourApp.Models
{
    public class UserRegistration
    {
        [Required(ErrorMessage = "Username is required.")]
        [StringLength(50, ErrorMessage = "Username cannot be longer than 50 characters.")]
        public string Username { get; set; }

        [Required(ErrorMessage = "Email is required.")]
        [EmailAddress(ErrorMessage = "Invalid email address format.")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Password is required.")]
        [StringLength(100, MinimumLength = 6, ErrorMessage = "Password must be at least 6 characters long.")]
        public string Password { get; set; }
    }
}
            
Note: Data annotations are primarily used for client-side and server-side validation. ASP.NET Core's model binding system automatically applies these validations when data is submitted to your application.

ViewModel vs. Model

While models represent the core data and business logic, ViewModels are classes specifically designed to hold data that a particular view needs to display. They can aggregate data from multiple models or transform data from a model into a format suitable for the view.

When to use ViewModels:

Example ViewModel:


namespace YourApp.ViewModels
{
    public class ProductDetailsViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string DisplayPrice { get; set; } // Formatted price
        public string ShortDescription { get; set; }
        public List<string> RelatedProductNames { get; set; }
    }
}
            
Tip: AutoMapper is a popular library that can help automate the mapping between models and ViewModels, reducing boilerplate code.

Working with Models in Controllers and Views

Controllers are responsible for interacting with models, retrieving data, and passing it to views. Views then use this data to render the UI.

Controller Example:


using Microsoft.AspNetCore.Mvc;
using YourApp.Models;
using YourApp.Services; // Assuming a service to get data

public class ProductController : Controller
{
    private readonly IProductService _productService;

    public ProductController(IProductService productService)
    {
        _productService = productService;
    }

    public IActionResult Details(int id)
    {
        var product = _productService.GetProductById(id);
        if (product == null)
        {
            return NotFound();
        }
        // You might map to a ViewModel here for complex views
        return View(product);
    }
}
            

View Example (Razor):


@model YourApp.Models.Product

@{
    ViewData["Title"] = Model.Name;
}

@Model.Name

Price: @Model.Price.ToString("C")

@Model.Description

By effectively defining and using models, you create a robust and maintainable ASP.NET Core application that separates concerns and promotes code reusability.