C# MVC Pattern
Introduction
The Model-View-Controller (MVC) pattern is a fundamental architectural design pattern in modern web development, particularly popular in C# applications through the ASP.NET MVC framework. MVC divides an application into three interconnected components, each with specific responsibilities, which leads to better organized code, improved maintainability, and enhanced scalability.
In this tutorial, we'll explore:
- What the MVC pattern is and why it's useful
- How each component (Model, View, Controller) works
- How to implement MVC in C# using ASP.NET MVC
- Real-world applications and best practices
What is MVC?
MVC is an architectural pattern that separates an application into three main components:
- Model - Represents your data and business logic
- View - Displays the data to the user (the UI)
- Controller - Handles user input and coordinates between Model and View
This separation of concerns makes your code more organized, easier to test, and simpler to maintain.
Components of MVC
Model
The Model represents the application's data and business logic. It:
- Contains data, state, and application logic
- Is independent of the user interface
- Notifies the View when data changes
- Processes data from the Controller
View
The View is responsible for presenting data to users:
- Displays the Model data to the user
- Sends user actions to the Controller
- Is typically implemented as HTML, CSS, and limited logic
- Can be multiple views for the same data
Controller
The Controller acts as an intermediary between Model and View:
- Processes incoming requests
- Manipulates data using the Model
- Selects which View to render
- Passes data from the Model to the View
Implementing MVC in C# with ASP.NET MVC
Let's create a simple example of an MVC application for managing a book collection:
1. Setting Up the Project
First, create a new ASP.NET MVC project in Visual Studio:
- Open Visual Studio
- Select "Create a new project"
- Choose "ASP.NET Core Web Application"
- Name your project "BookCollection" and click "Create"
- Select "Web Application (Model-View-Controller)" and click "Create"
2. Creating the Model
Let's create a simple Book model:
// Models/Book.cs
namespace BookCollection.Models
{
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public int Year { get; set; }
public string Genre { get; set; }
}
}
3. Creating the Controller
Next, let's create a controller to handle book operations:
// Controllers/BooksController.cs
using BookCollection.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace BookCollection.Controllers
{
public class BooksController : Controller
{
// In a real app, this would come from a database
private static List<Book> _books = new List<Book>
{
new Book { Id = 1, Title = "Clean Code", Author = "Robert C. Martin", Year = 2008, Genre = "Programming" },
new Book { Id = 2, Title = "Design Patterns", Author = "Erich Gamma et al.", Year = 1994, Genre = "Programming" },
new Book { Id = 3, Title = "The Pragmatic Programmer", Author = "Andrew Hunt & David Thomas", Year = 1999, Genre = "Programming" }
};
// GET: /Books/
public IActionResult Index()
{
return View(_books);
}
// GET: /Books/Details/5
public IActionResult Details(int id)
{
var book = _books.Find(b => b.Id == id);
if (book == null)
{
return NotFound();
}
return View(book);
}
}
}
4. Creating the Views
Now, let's create the views to display our books:
Index View (displays all books):
<!-- Views/Books/Index.cshtml -->
@model IEnumerable<BookCollection.Models.Book>
@{
ViewData["Title"] = "Book Collection";
}
<h1>Book Collection</h1>
<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Genre</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var book in Model) {
<tr>
<td>@book.Title</td>
<td>@book.Author</td>
<td>@book.Year</td>
<td>@book.Genre</td>
<td>
<a asp-action="Details" asp-route-id="@book.Id">Details</a>
</td>
</tr>
}
</tbody>
</table>
Details View (displays information about a specific book):
<!-- Views/Books/Details.cshtml -->
@model BookCollection.Models.Book
@{
ViewData["Title"] = "Book Details";
}
<h1>Book Details</h1>
<div>
<h4>@Model.Title</h4>
<hr />
<dl class="row">
<dt class="col-sm-2">Title</dt>
<dd class="col-sm-10">@Model.Title</dd>
<dt class="col-sm-2">Author</dt>
<dd class="col-sm-10">@Model.Author</dd>
<dt class="col-sm-2">Year</dt>
<dd class="col-sm-10">@Model.Year</dd>
<dt class="col-sm-2">Genre</dt>
<dd class="col-sm-10">@Model.Genre</dd>
</dl>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>