<目次>
(1) ASP.NETでViewに値を渡す方法
(1-1) 方法1:アクションメソッドの引数に追加
(1-2) 方法2:ViewBagを使う方法
(1-3) 方法3:ビューデータディクショナリを使用(オススメ度:低)
(1-4) サンプルプログラム
(1) ASP.NETでViewに値を渡す方法
(1-1) 方法1:アクションメソッドの引数に追加
Viewに渡したいオブジェクトを、アクションメソッドの引数として渡す方法です。
●構文
var textbook1 = new TextBook() { Name = "理科" };
return View(textbook1);
<!-- 方法1 --> <h2>方法1:@Model.Name</h2>
(1-2) 方法2:ViewBagを使う方法
●構文
var textbook2 = new TextBook() { Name = "算数" };
// ランタイム(実行時)にViewBagに追加される
ViewBag.TextBook2 = textbook2;
<h2>方法2:@ViewBag.TextBook2.Name</h2>
(1-3) 方法3:ビューデータディクショナリを使用(オススメ度:低)
●構文
var textbook3 = new TextBook() { Name = "社会" };
ViewData["TextBook"] = textbook3;
@using BookLibrarySystem.Models <h2>方法3:@( ((TextBook)ViewData["TextBook"]).Name )</h2>
●備考
(1-4) サンプルプログラム
●Controller
using BookLibrarySystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace BookLibrarySystem.Controllers
{
public class HomeController : Controller
{
// GET: TextBooks/Trend
public ActionResult Index()
{
//# 方法2:ViewBagを使用
var textbook2 = new TextBook() { Name = "算数" };
ViewBag.TextBook2 = textbook2;
//# 方法3:ビューデータディクショナリを使用
//# 各Dictionaryの中身はObjectである(Equals,ToStringなど)
var textbook3 = new TextBook() { Name = "社会" };
ViewData["TextBook3"] = textbook3;
//# 方法1:アクションメソッドの引数に追加
var textbook1 = new TextBook() { Name = "理科" };
return View(textbook1);
}
}
}

●View
@model BookLibrarySystem.Models.TextBook
<!-- 方法1 -->
<h2>方法1:@Model.Name</h2>
<!-- 方法2 -->
<h2>方法2:@ViewBag.TextBook2.Name</h2>
<!-- 方法3 -->
@using BookLibrarySystem.Models
<h2>方法3:@( ((TextBook)ViewData["TextBook3"]).Name )</h2>
@{
ViewBag.Title = "Home Index";
}
<div class="jumbotron">
<h3>本文</h3>
<p class="lead">あああああああ</p>
</div>

