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:
- Representing the application's data structure.
- Encapsulating business rules and validation logic.
- Interacting with data sources (e.g., databases, APIs).
Understanding Model Responsibilities
A well-designed model should:
- Contain Data: Properties that define the structure of the data (e.g., user information, product details).
- Contain Business Logic: Methods that perform operations on the data or enforce business rules.
- Not Contain Presentation Logic: Models should not be aware of how the data will be displayed. This is the responsibility of the View.
- Not Contain Request/Response Logic: Models should not directly handle HTTP requests or responses. This is the Controller's job.
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:
[Required]
: Specifies that a data field is mandatory.[StringLength]
: Validates the length of a string property.[Range]
: Validates that a numeric or date value falls within a specified range.[EmailAddress]
: Validates that a string is a valid email address format.
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."