ASP.NET Core MVC Models

In the Model-View-Controller (MVC) architectural pattern, the Model represents the application's data and the business logic that operates on that data. In ASP.NET Core MVC, models are typically represented by plain C# classes (POCOs - Plain Old CLR Objects). They are independent of the View and Controller and are responsible for:

Understanding Model Responsibilities

A well-designed model should:

Creating a Simple Model

Let's create a simple Product model:


namespace MvcMovie.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 data annotations that can be applied to model properties to define validation rules. These are essential for ensuring data integrity before it's processed by the application or stored in a database. Common data annotations include:

Example with Data Annotations:


using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int Id { get; set; }

        [StringLength(60, MinimumLength = 3)]
        [Required]
        public string Title { get; set; }

        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }

        [RegularExpression(@"^[A-Z]+[a-zA-Z0-9""'\s-]*$")]
        [StringLength(30)]
        [Required]
        public string Genre { get; set; }

        [Range(1, 100)]
        [DataType(DataType.Currency)]
        public decimal Price { get; set; }
    }
}
            

Working with Models in Controllers

Controllers use models to retrieve, manipulate, and pass data to views. Data binding automatically maps incoming request data to model properties.


using Microsoft.AspNetCore.Mvc;
using MvcMovie.Models;
using System.Collections.Generic;
using System.Linq;

public class MoviesController : Controller
{
    // GET: Movies
    public IActionResult Index()
    {
        var movies = GetSampleMovies(); // In a real app, this would fetch from a DB
        return View(movies);
    }

    // GET: Movies/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Movies/Create
    [HttpPost]
    public IActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            // Save the movie to the database
            // Redirect to Index action
            return RedirectToAction(nameof(Index));
        }
        return View(movie); // Return view with validation errors
    }

    private List<Movie> GetSampleMovies()
    {
        return new List<Movie>
        {
            new Movie { Id = 1, Title = "The Shawshank Redemption", Genre = "Drama", Price = 9.99M, ReleaseDate = new DateTime(1994, 9, 23) },
            new Movie { Id = 2, Title = "The Godfather", Genre = "Crime", Price = 10.99M, ReleaseDate = new DateTime(1972, 3, 24) }
        };
    }
}
            

Models and Databases

Models are central to data persistence. Technologies like Entity Framework Core are used to map models to database tables, allowing for easy creation, retrieval, update, and deletion (CRUD) operations.

Entity Framework Core Example:

The DbContext acts as a session with the database and allows you to query and save data. The model classes you define (like Movie) become entities that EF Core manages.


using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Movie> Movies { get; set; }
}
            
"Models are the heart of your application's data and logic, providing a clean separation of concerns that makes your code more maintainable and scalable."