ASP.NET Core MVC Fundamentals
This section covers the core concepts and building blocks of ASP.NET Core MVC, a powerful framework for building modern, testable, and maintainable web applications.
What is ASP.NET Core MVC?
ASP.NET Core MVC is an open-source framework built on ASP.NET Core that enables the creation of dynamic websites and web applications. It follows the Model-View-Controller (MVC) architectural pattern, separating concerns into three interconnected parts:
- Model: Represents the application's data and business logic. It's responsible for managing data, responding to instructions from the controller, and validating data.
- View: Responsible for presenting data to the user. It's typically HTML, CSS, and JavaScript, with Razor syntax for dynamically generating content.
- Controller: Acts as the intermediary between the Model and the View. It handles user input, interacts with the Model to retrieve or update data, and selects the appropriate View to render the response.
The MVC Request Lifecycle
Understanding how a request is processed through the MVC pipeline is crucial:
- The user makes a request to the web server.
- The ASP.NET Core application receives the request.
- The routing engine matches the request URL to a specific route defined in the application's configuration.
- The route maps the URL to a controller and an action method.
- The controller's action method is executed. This method might interact with the Model to fetch or process data.
- The action method returns a result, such as a
ViewResult
,RedirectResult
, orJsonResult
. - If a
ViewResult
is returned, the specified View is rendered. The View uses data passed from the controller (often via a ViewModel) to generate HTML. - The generated HTML, along with CSS and JavaScript, is sent back to the user's browser.
Key Components
Controllers
Controllers are plain old C# classes that inherit from Controller
or ControllerBase
. They contain public methods called action methods, which handle incoming requests. Action methods typically return an IActionResult
.
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
public IActionResult Index()
{
// Logic to prepare data for the view
var message = "Welcome to ASP.NET Core MVC!";
return View("Index", message); // Renders the Index.cshtml view
}
public IActionResult About()
{
return View(); // Renders About.cshtml view by convention
}
}
Views
Views are typically Razor files (.cshtml
) that contain a mix of HTML markup and C# code. They are responsible for the presentation layer.
@* Views/Home/Index.cshtml *@
@model string
@{
ViewData["Title"] = "Home Page";
}
<h1>@Model</h1>
<p>This is a basic ASP.NET Core MVC application.</p>
Models
Models can be simple POCO (Plain Old CLR Object) classes that represent your data, or they can include business logic and data access code. For complex applications, it's common to use ViewModels to shape data specifically for a View.
// Example Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
// Example ViewModel
public class ProductViewModel
{
public string ProductName { get; set; }
public decimal ProductPrice { get; set; }
}
Routing
Routing in ASP.NET Core MVC maps incoming request URLs to action methods in your controllers. It's configured in the Program.cs
(or Startup.cs
in older versions) file using the endpoint routing middleware.
// In Program.cs (for .NET 6 and later)
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews(); // Enables MVC
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"); // Default route
app.Run();
Next Steps
Continue exploring related documentation: