Bài 1: Giới thiệu về Trình quản lý quảng cáo
TẠO CONTROLLER, ACTION, VIEW & ĐIỀU HƯỚNG TRANG TRONG ASP.NET CORE MVC (VISUAL STUDIO)
🎯 1. Mục tiêu
✅ Tạo controller, action, view bằng Visual Studio
✅ Tạo nhiều view, điều hướng qua lại bằng <a> và ActionLink
✅ Thiết lập custom router để URL thân thiện
🚀 2. Tạo Controller
➕ Tạo Controller bằng Visual Studio
-
Mở Solution Explorer, click phải thư mục Controllers → Add → Controller…
-
Chọn MVC Controller - Empty, đặt tên:
PageController -
Visual Studio tạo sẵn:
public class PageController : Controller
{
public IActionResult Index()
{
return View();
}
}
⚙️ 3. Thêm nhiều Action
public IActionResult About()
{
return View();
}
public IActionResult Contact()
{
return View();
}
🎨 4. Tạo nhiều View tương ứng
➕ Tạo View bằng Visual Studio
-
Click phải vào
return View();→ Add View… -
Đặt tên:
-
Index→ cho Index -
About→ cho About -
Contact→ cho Contact
-
-
Template: Empty (without model)
🔗 5. Điều hướng giữa các trang
👉 Dùng thẻ <a> Trong Index.cshtml:
<h1>Home Page</h1>
<a href="/Page/About">Go to About</a>
<a href="/Page/Contact">Go to Contact</a>
👉 Dùng @Html.ActionLink (router tự sinh URL)
<h1>Home Page</h1>
@Html.ActionLink("Go to About", "About", "Page")
@Html.ActionLink("Go to Contact", "Contact", "Page")
🚦 6. Custom router để URL thân thiện
⚙️ Sửa Program.cs (hoặc Startup.cs)
Thay vì URL mặc định /Page/About, ta có thể định nghĩa route đẹp hơn:
app.MapControllerRoute(
name: "custom",
pattern: "{page}/{action=Index}/{id?}",
defaults: new { controller = "Page" }
);
👉 Bây giờ URL sẽ là:
-
/about→ gọiPageController.About() -
/contact→ gọiPageController.Contact()
✅ Muốn vậy cần đặt route name khớp với action
Ví dụ gọi /about sẽ map sang {page} = about, map tới controller Page.
Hoặc có thể đặt rõ route cho từng action:
[Route("about-us")]
public IActionResult About()
{
return View();
}
-
URL
/about-ussẽ gọi trực tiếp actionAbout.
🚀 7. Demo hoàn chỉnh
📂 Controller
public class PageController : Controller
{
public IActionResult Index()
{
return View();
}
[Route("about-us")]
public IActionResult About()
{
return View();
}
[Route("contact-us")]
public IActionResult Contact()
{
return View();
}
}
📄 Views/Page/Index.cshtml
<h1>Home Page</h1>
<a href="/about-us">About</a>
<a href="/contact-us">Contact</a>
📄 Views/Page/About.cshtml
<h1>About Page</h1>
<a href="/">Back Home</a>
📄 Views/Page/Contact.cshtml
<h1>Contact Page</h1>
<a href="/">Back Home</a>
Bài tập số 4: WebDaoTao
Yêu cầu:
-
Tạo Controller Video với các action cơ bản: tất cả trả về view bình thường
-
DanhSach(): Hiển thị danh sách video. -
Xem(int id): Xem chi tiết video -
Them(): Hiển thị form thêm video -
Sua(int id): Hiển thị form sửa video -
Xoa(int id): Xóa video.
-
-
Tạo View:
-
Hiển thị danh sách tin tức theo nhiều kiểu: View thông thường
-
Nộp bài:
-
Nén project đã làm và nộp file.