ASP.NET Core - ViewBag

ViewBag

  • ViewBag 是一個 container
    public class CategoriesController : Controller
    {
        // /categories/index
        public IActionResult Index()
        {
            // return views/index.cshtml
            return View();
        }

        // /categories/details/{string: category}
        public IActionResult Details(string category)
        {
            // store the selected product name in the ViewBag container
            // ViewBag is automatically passed back to the view that loads
            ViewBag.category = category;
            // return a view that is in views/categories/details.cshtml
            return View(); 
        }
    }
  • /views/categories/details.cshtml
@{
    ViewData["Title"] = "Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

// 這裡就可以 catch 到 ViewBag 裡面的東西
<h1>@ViewBag.category Details</h1>
  • 在網頁上的 url 會是 /categories/details/category=Food
    • asp-controller="Categories" : 表示是在 CategoriesController
    • asp-action : 找到 Details() 這一個 Action 或者是 function()
    • asp-route-category="Food" : 可以 pass 到 url

@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Please choose a Product</h1>

<ul>
    <li>
        <a asp-controller="Categories" asp-action="Details" asp-route-category="Food">Food</a>
    </li>
    <li>
        <a asp-controller="Categories" asp-action="Details" asp-route-category="Tech">Tech</a>
    </li>
    <li>
        <a asp-controller="Categories" asp-action="Details" asp-route-category="Sports">Sports</a>
    </li>
</ul>

留言