關於 部分檢視

問題: 請開啟台灣高鐵網頁
    1. 觀察導覽列
        我們已經透過 pchome 討論過導覽列應該要規劃在 Layout
    2. 觀察 右下角|右邊中間 的區塊有三個小功能
        這樣的功能是否應該要放在 Layout?

練習:
    1. 建立 Controller TestPartialView 和檢視頁面
        TestPartialViewController.cs

    2. 在 Controller 底下建立三個 Action 和對應的檢視頁面
        Shiro 、 Nanako 、 Himawari

    3. 在 Controller 傳遞測試資料 到 上述三個檢視頁面
        (用以確認頁面可以正常呼叫且顯示)

    4. 確認專案 和 三個檢視頁面 皆可正常運行

    <https://localhost>:XXXX/TestPartialView/Shiro
    <https://localhost>:XXXX/TestPartialView/Nanako
    <https://localhost>:XXXX/TestPartialView/Himawari


這是解決部分檢視的練習步驟,並基於 MVC 框架建立 Controller 和檢視頁面的詳細過程:

步驟 1: 建立 TestPartialViewController.cs

首先,你需要在專案的 Controllers 資料夾中建立一個新的 Controller,名為 TestPartialViewController

using System.Web.Mvc;

namespace YourNamespace.Controllers
{
    public class TestPartialViewController : Controller
    {
        // Action for Shiro
        public ActionResult Shiro()
        {
            ViewBag.Message = "This is Shiro's partial view.";
            return View();
        }

        // Action for Nanako
        public ActionResult Nanako()
        {
            ViewBag.Message = "This is Nanako's partial view.";
            return View();
        }

        // Action for Himawari
        public ActionResult Himawari()
        {
            ViewBag.Message = "This is Himawari's partial view.";
            return View();
        }
    }
}

在這個 Controller 中,我們定義了三個 Action (ShiroNanakoHimawari),每個 Action 都傳遞一個測試訊息至對應的檢視頁面。


步驟 2: 建立三個對應的檢視頁面

接著,你需要為每個 Action 建立一個對應的 View。在 Views\\\\TestPartialView 資料夾下建立三個檔案,分別命名為 Shiro.cshtmlNanako.cshtmlHimawari.cshtml

Shiro.cshtml

@{
    Layout = null;
}
<h2>@ViewBag.Message</h2>

Nanako.cshtml

@{
    Layout = null;
}
<h2>@ViewBag.Message</h2>

Himawari.cshtml

@{
    Layout = null;
}
<h2>@ViewBag.Message</h2>

這三個檢視頁面只顯示了從 ViewBag 傳遞過來的訊息,可以簡單測試這些頁面是否可以正常運行。