<目次>
(1) ASP.NETのViewBagとは?構文やサンプルプログラムもご紹介
(1-1) 概要
(1-2) 構文
(1-3) サンプルプログラム
(1) ASP.NETのViewBagとは?構文やサンプルプログラムもご紹介
(1-1) 概要
ViewBagは「ビュー変数」とも呼ばれ、ASP.NET MVCにおけるViewBagはモデル(Model)に含まれない「一時的なデータ」をController⇒Viewに連携する目的で使用します。
(1-2) 構文
●Controller側
ViewBagに対して、次のように値をセットします。変数の名前は命名規則に沿う範囲で自由に命名可能です。
ViewBag.変数名 = 設定値;
●View側
HTML中の値を埋め込む箇所にて次のように記述します。
@ViewBag.変数名
(補足)もう1つの表記方法について
ViewBagには同じ意味の別の書き方があり、次の「ViewData」クラスを記述する事も可能です。
●Controller側
ViewData[“変数名”] = 設定値;
●View側
@ViewData[“変数名”]
(1-3) サンプルプログラム
(1-3-1) Index.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ViewBag Test</title>
</head>
<body>
<div>HelloWorld</div>
<div>@ViewBag.Name1</div>
<div>@ViewData["Name2"]</div>
</body>
</html>
(図131)

(1-3-2) Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCTest.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
ViewBag.Name1 = "abcdefg";
ViewData["Name2"] = "hijklmn";
return View();
}
}
}
(図132)

<実行結果>
・ControllerでセットしたViewBagの値が正しく取得出来ている事が確認できます。
(図133)
