Introduction to ASP.NET Core MVC
ASP.NET Core MVC is a popular open-source framework for building modern, web-based applications and APIs. It leverages the Model-View-Controller (MVC) architectural pattern, providing a clean separation of concerns and promoting testable, maintainable code.
This documentation provides an in-depth guide to understanding and utilizing the features of ASP.NET Core MVC.
The Model-View-Controller (MVC) Pattern
The MVC pattern divides an application into three interconnected components:
- Model: Represents the application's data and business logic. It is responsible for managing the data and responding to requests for the data.
- View: Responsible for presenting the data to the user. It typically generates HTML, CSS, and JavaScript to display the UI. Views have no knowledge of controllers or models directly, but they can access data passed to them by the controller.
- Controller: Acts as an 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.
This separation makes it easier to manage complexity and allows for parallel development by different team members.
Controllers
Controllers are C# classes that handle incoming HTTP requests. They typically inherit from Controller
or ApiController
(for API-focused applications).
A controller contains action methods, which are public methods that are executable by the framework.
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
public IActionResult Index()
{
return View(); // Renders the Index.cshtml view
}
public IActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
}
Views
Views are typically Razor files (.cshtml
) that contain HTML markup, along with C# code and directives to dynamically generate HTML.
Razor syntax allows you to embed server-side code within HTML using the @
symbol.
@model MyWebApp.Models.HomeViewModel
@{
ViewData["Title"] = "Home Page";
}
<div class="jumbotron">
<h1>@Model.WelcomeMessage</h1>
<p class="lead">Discover the power of ASP.NET Core MVC.</p>
<a href="#" class="btn btn-primary btn-lg">Learn More »</a>
</div>
<div class="row">
<div class="col-md-4">
<h2>@Model.Feature1.Title</h2>
<p>@Model.Feature1.Description</p>
</div>
<div class="col-md-4">
<h2>@Model.Feature2.Title</h2>
<p>@Model.Feature2.Description</p>
</div>
<div class="col-md-4">
<h2>@Model.Feature3.Title</h2>
<p>@Model.Feature3.Description</p>
</div>
</div>
Models
Models are plain old C# objects (POCOs) that represent the data and business logic of your application. They can include properties, methods, and validation logic.
namespace MyWebApp.Models
{
public class HomeViewModel
{
public string WelcomeMessage { get; set; }
public FeatureViewModel Feature1 { get; set; }
public FeatureViewModel Feature2 { get; set; }
public FeatureViewModel Feature3 { get; set; }
}
public class FeatureViewModel
{
public string Title { get; set; }
public string Description { get; set; }
}
}
Routing
Routing maps incoming HTTP requests to specific action methods on controllers. ASP.NET Core MVC uses a routing system that can be configured in Startup.cs
(or Program.cs
in .NET 6+).
The default convention uses a URL pattern like /ControllerName/ActionName/Parameter
.
// In Startup.cs or Program.cs
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Action Methods
Action methods are public methods within a controller that handle specific HTTP requests. They return an IActionResult
, which represents the result of the action.
Common return types include:
ViewResult
: Returns an HTML view.RedirectResult
: Redirects the browser to a different URL.ContentResult
: Returns plain text.JsonResult
: Returns JSON data.StatusCodeResult
: Returns an HTTP status code.
View Data and Temp Data
View Data and Temp Data are mechanisms for passing data from the controller to the view.
ViewData
: A dictionary-like object that stores data for a single request. It's weakly typed.ViewBag
: A dynamic wrapper aroundViewData
, offering a more convenient syntax.TempData
: Similar toViewData
but can persist data across multiple requests (typically used for redirecting after form submission).
Filters
Filters are attributes that can be applied to controllers or action methods to implement cross-cutting concerns such as authorization, logging, and error handling.
Common filter types include:
- Authorization filters
- Resource filters
- Action filters
- Result filters
- Exception filters
[Authorize] // Example of an Authorization filter
public class AdminController : Controller
{
// ...
}
Tag Helpers
Tag Helpers are a powerful feature that allows you to write server-side code in Razor views using HTML-like tags. They enhance productivity and improve the readability of your views.
Examples include:
<form asp-controller="Home" asp-action="Create" method="post">
<input asp-for="UserName" />
<a asp-controller="Product" asp-action="Details" asp-route-id="123">View Product</a>
View Components
View Components are similar to Partial Views but are more powerful and can contain logic. They are ideal for reusable UI components.
They consist of a ViewComponent
class and a corresponding Razor view.