ASP.NET Core Models

This document provides a comprehensive guide to understanding and implementing models in ASP.NET Core applications. Models represent the data and business logic of your application. They are a core component of the Model-View-Controller (MVC) and Razor Pages patterns.

What are Models?

In ASP.NET Core, a model is typically a plain old CLR object (POCO) that encapsulates the data and related business logic. Models are responsible for:

Creating Models

Models are usually defined as C# classes. You can create them in your project's Models folder.

Example: A Simple 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 Validation

ASP.NET Core integrates seamlessly with data validation. You can use attributes from the System.ComponentModel.DataAnnotations namespace to enforce validation rules on your model properties.

Example: Adding Validation Attributes


using System.ComponentModel.DataAnnotations;

namespace YourApp.Models
{
    public class Product
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "Product name is required.")]
        [StringLength(100, ErrorMessage = "Product name cannot exceed 100 characters.")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Price is required.")]
        [Range(0.01, double.MaxValue, ErrorMessage = "Price must be greater than zero.")]
        public decimal Price { get; set; }

        public string Description { get; set; }
    }
}
        

Note: When using validation attributes, ensure you have the necessary NuGet packages installed and that you configure model validation in your application's startup.

Models in MVC

In the Model-View-Controller (MVC) pattern, models are passed to views for display. Controllers are responsible for retrieving data, potentially manipulating it using the model, and then passing it to the appropriate view.

Controller Example:


using Microsoft.AspNetCore.Mvc;
using YourApp.Models;
using YourApp.Services; // Assuming a service to get product 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();
        }
        return View(product); // Pass the product model to the view
    }
}
        

View Example (Razor):


@model YourApp.Models.Product

@{
    ViewData["Title"] = "Product Details";
}

@Model.Name

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

@Model.Description

Back to List

Models in Razor Pages

In Razor Pages, models are represented by the PageModel class. The PageModel contains properties and handlers that manage the page's data and logic.

PageModel Example:


using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc;
using YourApp.Models;
using YourApp.Services;

public class ProductDetailsModel : PageModel
{
    private readonly IProductService _productService;

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

    [BindProperty]
    public Product Product { get; set; }

    public IActionResult OnGet(int id)
    {
        Product = _productService.GetProductById(id);
        if (Product == null)
        {
            return NotFound();
        }
        return Page(); // Render the Razor Page
    }
}
        

Razor Page Example (.cshtml):


@page
@model YourApp.Pages.ProductDetailsModel

@{
    ViewData["Title"] = "Product Details";
}

@Model.Product.Name

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

@Model.Product.Description

Back to List

Tip: You can use data annotations for validation in Razor Pages just like in MVC. The model binding system automatically handles validation based on these attributes.

Data Access and Models

Models often interact with data sources. Common approaches include:

It's a common practice to separate data access logic into dedicated services or repositories, keeping your models focused on data representation and business rules.

Next Steps

Explore related topics to further enhance your understanding: