如何使用 ASP .Net MVC C# 中的 ViewBag?


ViewBag 使用 C# 4.0 中引入的動態特性。它允許動態地向物件新增屬性。在內部,它是由 ControllerBase 類的一個動態型別屬性,後者是 Controller 類的基類。

ViewBag 僅將資料從控制器傳輸到檢視,反之則不然。如果發生重定向,ViewBag 值將為 null。ViewBag 能夠動態地設定和獲取值,並且能夠無需將其轉換為強型別而新增任意數量的附加欄位。

將資料儲存在 ViewBag 中 −

ViewBag.Counties = countriesList;

從 ViewBag 中檢索資料 −

string country = ViewBag.Countries;

控制器

示例

using System.Collections.Generic;
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public ViewResult Index(){
         ViewBag.Countries = new List<string>{
            "India",
            "Malaysia",
            "Dubai",
            "USA",
            "UK"
         };
         return View();
      }
   }
}

檢視

@{
   ViewBag.Title = "Countries List";
}
<h2>Countries List</h2>
<ul>
@foreach(string country in ViewBag.Countries){
   <li>@country</li>
}
</ul>

輸出

更新於:2020 年 9 月 24 日

3K+ 瀏覽量

開啟你的 事業

完成課程並獲得認證

開始
廣告