Understanding Models in ASP.NET Core MVC
Models are a fundamental part of the Model-View-Controller (MVC) architectural pattern. In ASP.NET Core MVC, models represent the data and the business logic of your application. They are responsible for managing the application's state and responding to requests for information.
What is a Model?
A model typically encapsulates the data that flows between the model, the view, and the controller. It can:
- Represent data entities (e.g., a
Product
, aUser
). - Contain validation rules for the data.
- Implement business logic (e.g., calculating prices, processing orders).
- Interact with data sources like databases or APIs.
Creating Your First Model
Let's create a simple model to represent a book:
namespace MyWebApp.Models
{
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public int PublicationYear { get; set; }
}
}
This Book
class is a plain old C# object (POCO) that serves as our model. It has properties to hold the book's data.
Using Models in Controllers
Controllers act as intermediaries. They receive requests, interact with models to retrieve or update data, and then select a view to render the response.
Here's an example of a controller that uses the Book
model:
using Microsoft.AspNetCore.Mvc;
using MyWebApp.Models;
using System.Collections.Generic;
namespace MyWebApp.Controllers
{
public class BooksController : Controller
{
public IActionResult Index()
{
// In a real application, you would fetch this data from a database or other source.
var books = new List
{
new Book { Id = 1, Title = "The Hitchhiker's Guide to the Galaxy", Author = "Douglas Adams", PublicationYear = 1979 },
new Book { Id = 2, Title = "Pride and Prejudice", Author = "Jane Austen", PublicationYear = 1813 },
new Book { Id = 3, Title = "1984", Author = "George Orwell", PublicationYear = 1949 }
};
return View(books); // Pass the list of books to the view
}
public IActionResult Details(int id)
{
// In a real application, you would fetch a specific book by its ID.
var book = new Book { Id = id, Title = "Sample Book", Author = "Anonymous", PublicationYear = 2023 };
return View(book); // Pass the specific book to the view
}
}
}
Creating Views for Models
Views are responsible for displaying the data provided by the model. You can use Razor syntax to embed C# code within your HTML.
For the Index
action in the BooksController
, you might have a view at Views/Books/Index.cshtml
:
@model IEnumerable<MyWebApp.Models.Book>
@{
ViewData["Title"] = "Book List";
}
<h2>Book Catalog</h2>
<table class="table">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.First().Title)</th>
<th>@Html.DisplayNameFor(model => model.First().Author)</th>
<th>@Html.DisplayNameFor(model => model.First().PublicationYear)</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var book in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => book.Title)</td>
<td>@Html.DisplayFor(modelItem => book.Author)</td>
<td>@Html.DisplayFor(modelItem => book.PublicationYear)</td>
<td>
@Html.ActionLink("Details", "Details", new { id = book.Id })
</td>
</tr>
}
</tbody>
</table>
- Models encapsulate data and business logic.
- Controllers handle requests and orchestrate interactions between models and views.
- Views present data from models to the user.
- Razor syntax allows embedding C# code in HTML.
Model Validation
ASP.NET Core MVC provides robust support for data validation. You can use data annotations to define validation rules directly on your model properties.
Let's add some validation to our Book
model:
using System.ComponentModel.DataAnnotations;
namespace MyWebApp.Models
{
public class Book
{
public int Id { get; set; }
[Required(ErrorMessage = "Title is required.")]
[StringLength(100, ErrorMessage = "Title cannot exceed 100 characters.")]
public string Title { get; set; }
[Required(ErrorMessage = "Author is required.")]
[StringLength(50, ErrorMessage = "Author name cannot exceed 50 characters.")]
public string Author { get; set; }
[Required(ErrorMessage = "Publication year is required.")]
[Range(1000, 2100, ErrorMessage = "Please enter a valid publication year.")]
public int PublicationYear { get; set; }
}
}
When you submit a form using this model, ASP.NET Core MVC will automatically perform these validations. You can then display validation errors in your view.
Next Steps: Explore advanced model binding, data access with Entity Framework Core, and more complex validation scenarios.