ASP.NET Core MVC Basics
This tutorial guides you through the fundamental concepts of the Model-View-Controller (MVC) architectural pattern in ASP.NET Core. MVC is a popular framework for building web applications that separates an application into three interconnected components: Models, Views, and Controllers.
What is MVC?
The Model-View-Controller (MVC) architectural pattern is an approach to designing and developing applications. It separates an application into three logical components:
- Model: Represents the data and the business logic of the application. It's responsible for managing data, state, and rules.
- View: Responsible for presenting the data to the user. It's the user interface of the application and typically renders HTML.
- 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 display the result.
The MVC Flow
Here's a typical flow of an MVC request:
- The user sends a request to the application (e.g., by clicking a link or submitting a form).
- The ASP.NET Core routing mechanism maps the incoming request to a specific Controller and Action method.
- The Controller's Action method is executed. It may interact with the Model to fetch or process data.
- The Controller selects a View to render the response.
- The View is rendered, using the data provided by the Controller and Model, to generate an HTML response.
- The HTML response is sent back to the user's browser.
Creating a Simple MVC Application
Let's create a basic ASP.NET Core MVC application.
Step 1: Create a New Project
Open your terminal or command prompt and run the following .NET CLI command:
dotnet new mvc -o MyMvcApp
This command creates a new directory named MyMvcApp
and generates a default ASP.NET Core MVC project within it.
Step 2: Understanding the Project Structure
Navigate into the MyMvcApp
directory. You'll find several important folders:
- Controllers: Contains your controller classes.
- Models: Contains your model classes.
- Views: Contains your view files (
.cshtml
files). This folder is further organized by controller name (e.g.,Views/Home
) and aShared
folder for common views. - wwwroot: Contains static files like CSS, JavaScript, and images.
Step 3: Exploring the Default Controller
Open the Controllers/HomeController.cs
file. You'll see a simple controller:
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using MyMvcApp.Models;
namespace MyMvcApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
The Index()
method returns a ViewResult
, which tells ASP.NET Core to render the Index.cshtml
view associated with this controller.
Step 4: Exploring the Default View
Open the Views/Home/Index.cshtml
file. This is the view that gets rendered by the Index()
action:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
Welcome
Learn about building Web apps with ASP.NET Core.
The @
symbol is used for Razor syntax, allowing you to embed server-side C# code within your HTML. In this case, @ViewData["Title"]
sets the page title.
Step 5: Running the Application
In your terminal, navigate back to the project root directory (MyMvcApp
) and run:
dotnet run
Open your web browser and go to https://localhost:5001
(or the port indicated by the CLI output). You should see the default ASP.NET Core MVC application.
[ResponseCache]
attribute in the Error()
action is used to control caching behavior for responses.
Next Steps
Now that you have a basic understanding of MVC, you can explore more advanced topics such as:
- Routing: How to define custom URL patterns.
- Data Binding: How to bind form data to model properties.
- Validation: Implementing data validation for models.
- Layouts and Partial Views: Reusing UI elements.