Model-View-Controller (MVC) in ASP.NET Core

The Model-View-Controller (MVC) architectural pattern separates an application into three interconnected components: the Model, the View, and the Controller. This separation of concerns helps manage the complexity of web applications. ASP.NET Core MVC provides a robust framework for building these applications.

What is MVC?

Key Concepts in ASP.NET Core MVC

Controllers

Controllers are C# classes that inherit from Controller. They contain action methods, which are public methods that handle incoming HTTP requests. Each action method typically corresponds to a specific task or functionality in the application.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";
        return View();
    }
}

Views

Views are typically implemented as .cshtml files, which combine HTML markup with C# code using the Razor syntax. They are responsible for rendering the UI and displaying data passed from the Controller.

@* Views/Home/Index.cshtml *@
@{
    ViewData["Title"] = "Home Page";
}

ASP.NET Core MVC

Welcome to your new ASP.NET Core MVC application!

Application uses

  • Sample pages using HTML, CSS, and JavaScript
  • Tag Helpers
  • Model binding
  • Client-side validation

Build tools

  • See the .csproj file for a list of NuGet packages.
  • Dynamically content generated by ASP.NET Core.
  • Web SDK and .NET CLI for building and publishing.

Overview

Learn more about ASP.NET Core at https://docs.microsoft.com/aspnet/core.

Models

Models can be simple C# classes (POCOs) that represent the data structure of your application. They can also include validation logic and methods for data access.

public class MessageViewModel
{
    public string Title { get; set; }
    public string Content { get; set; }
}

Routing

Routing in ASP.NET Core MVC maps incoming HTTP requests to specific action methods on Controllers. This is typically configured in the Startup.cs file using middleware like MapControllerRoute.

// In Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
    // ...
}

Further Reading