PRN222 - Chương 4: ASP.NET Core MVC
ASP.NET Core MVC trong PRN222: controller, action, IActionResult, ViewResult, PartialView và attribute HttpPost. Nội dung chương còn gồm directive @model cho strongly-typed view, cú pháp Razor, ViewData và ViewBag dùng chung một kho dữ liệu, bẫy ép kiểu InvalidCastException, model binding, model validation với ModelState.IsValid, attribute Bind và Compare, thư mục wwwroot chứa file tĩnh. Học xong chương này, người học dựng được một luồng MVC trọn vẹn từ controller tới view có kiểm tra dữ liệu.
Bắt đầu bằng Chế độ học nếu bạn muốn đáp án và giải thích hiện ngay sau mỗi câu — không bấm giờ, dừng lúc nào cũng được. Chọn Thi thử khi muốn biết mình đang ở đâu: có bấm giờ, chấm điểm ở cuối, và giải thích chỉ mở sau khi nộp.
Luyện tập theo chủ đề này
Câu hỏi của chủ đề
public IActionResult Save(Person person) {
if (ModelState.IsValid) return Content("Valid");
return Content("Error");
}If no value for Age is passed and Age is int, what happens?
public class Person {
public int Age { get; set; }
}
public IActionResult Save(Person person) {
if (!ModelState.IsValid) {
return Content("Invalid!");
}
return Content("OK");
}Input: Age = "abc"? What is the output?
public IActionResult Index() {
ViewData["User"] = "Admin";
return View();
}Razor: <p>@ViewBag.User</p> What is displayed?
AdminnullErrorNothingpublic IActionResult Index() {
ViewBag.Count = 10;
return View();
}Razor: <p>@(ViewBag.Count + 5)</p> What happens?
services.AddScoped<IRepository, CustomerRepository>();In an ASP.NET Core web app, how often is CustomerRepository created?
public IActionResult Index() {
ViewData["Count"] = "10";
return View();
}In Razor: <p>@((int)ViewData["Count"] + 5)</p> What happens?
// Controller
public IActionResult Index()
{
ViewBag.Message = "Hello from ViewBag!";
ViewData["Title"] = "My Page Title";
return View();
}
// View
<p>@ViewBag.Message</p>
<h1>@ViewData["Title"]</h1>// Controller
ViewData["Number"] = 123; // ViewData requires casting in the view.
ViewBag.Text = "Hello"; // ViewBag does not require casting.
//View
<p>Number: @((int)ViewData["Number"])</p>
<p>Text: @ViewBag.Text</p>Đề có câu hỏi của chủ đề này
4 đề chứa ít nhất một câu thuộc chủ đề — mở đề để làm cả bộ, không chỉ từng câu.