MVC tách ứng dụng thành Model (dữ liệu), View (giao diện) và Controller (điều khiển). Đây là kiến trúc phổ biến cho ứng dụng lớn và tương tự Laravel, Django. Bài này tạo dự án MVC và hiểu luồng xử lý.

55 phútTrung cấp
Bạn sẽ học được
  • Hiểu luồng Request → Controller → View
  • Tạo Controller và Action
  • Truyền model sang View
  • Định tuyến quy ước và thuộc tính

Cơ sở lý thuyết

MVC (Model–View–Controller) là mẫu kiến trúc do Trygve Reenskaug đề xuất năm 1979 tại Xerox PARC, tách ứng dụng thành ba vai trò theo nguyên lý tách biệt mối quan tâm (separation of concerns):

Thành phầnTrách nhiệmTrong ASP.NET Core
ModelDữ liệu và quy tắc nghiệp vụLớp C#, Entity, ViewModel
ViewHiển thịTệp .cshtml trong Views/
ControllerNhận yêu cầu, điều phối Model và chọn ViewLớp kế thừa Controller, mỗi phương thức public là một action
  • Định tuyến quy ước {controller=Home}/{action=Index}/{id?}: /SinhVien/ChiTiet/5 gọi SinhVienController.ChiTiet(5). Hoặc định tuyến thuộc tính [Route], [HttpGet].
  • Action trả về IActionResult: View(), RedirectToAction(), NotFound(), Json(), File().
  • ViewModel: lớp chuyên chở đúng dữ liệu một View cần, khác entity trong CSDL – tránh lộ trường nhạy cảm và lỗi gán hàng loạt (overposting).
  • Controller nên "mỏng": logic nghiệp vụ đặt trong service được tiêm qua DI.
  • Filter (bộ lọc) chạy trước/sau action để xử lý chung: phân quyền, ghi log, xử lý ngoại lệ.

Tạo dự án

dotnet new mvc -o QlsvMvc

Controller, Model, View

// Models/SinhVien.cs
public class SinhVien
{
    public int Id { get; set; }
    public string Ten { get; set; } = "";
    public double Diem { get; set; }
}

// Controllers/SinhVienController.cs
public class SinhVienController : Controller
{
    private static readonly List<SinhVien> ds = new()
    {
        new() { Id = 1, Ten = "Lan", Diem = 9 },
        new() { Id = 2, Ten = "Minh", Diem = 6.5 }
    };
    public IActionResult Index() => View(ds);
    public IActionResult ChiTiet(int id)
    {
        var sv = ds.FirstOrDefault(s => s.Id == id);
        return sv == null ? NotFound() : View(sv);
    }
}
@* Views/SinhVien/Index.cshtml *@
@model List<SinhVien>
@foreach (var sv in Model)
{
    <p><a asp-action="ChiTiet" asp-route-id="@sv.Id">@sv.Ten</a> - @sv.Diem</p>
}

Định tuyến

// Program.cs: /{controller=Home}/{action=Index}/{id?}
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");

Ví dụ /SinhVien/ChiTiet/2 gọi action ChiTiet với id = 2.

Razor Pages hay MVC?

Razor PagesMVC
Tổ chứcTheo trangTheo controller
Phù hợpỨng dụng vừa, form CRUDỨng dụng lớn, nhiều chức năng

Ứng dụng thực tế

Bài toán: chức năng xem bảng điểm: controller không truy vấn CSDL trực tiếp mà gọi service; dùng ViewModel chỉ chứa thông tin cần hiển thị; sinh viên chỉ xem được bảng điểm của chính mình:

public record BangDiemVM(string HoTen, string Lop, double DiemTB, List<(string Mon, double Diem)> Diem);

[Authorize]
public class BangDiemController(IDiemService diemService) : Controller
{
    // GET /BangDiem/Xem/2610010001
    public async Task<IActionResult> Xem(string id)
    {
        var maCuaToi = User.FindFirst("MaSV")?.Value;
        if (id != maCuaToi && !User.IsInRole("GiangVien")) return Forbid();

        BangDiemVM? vm = await diemService.LayBangDiemAsync(id);
        return vm is null ? NotFound() : View(vm);        // Views/BangDiem/Xem.cshtml
    }
}
// Program.cs: builder.Services.AddControllersWithViews(); builder.Services.AddScoped<IDiemService, DiemService>();
// app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
Thực hành
  1. Tạo SinhVienController với Index và ChiTiet.
  2. Tạo View hiển thị danh sách dạng bảng Bootstrap.
  3. Thêm action TimKiem(string q) lọc theo tên.
Tóm tắt bài học
  • Controller nhận yêu cầu, chọn View.
  • View hiển thị Model.
  • Đường dẫn mặc định {controller}/{action}/{id?}.