ViewDataとViewBag,を使用する、Controller側のコード例:
public async Task<IActionResult> Index()
{
ViewBag.Articles = await _context.skyArticle.OrderByDescending(a => a.Id).ToListAsync();
ViewBag.Genres = await _context.skyGenre.OrderByDescending(a => a.Id).Skip(0).Take(3).ToListAsync();
ViewData["Journals"] = (await _context.skyArticle.OrderByDescending(a => a.Id).ToListAsync());
return View(await _context.skyGenre.Include("skyArticles").ToListAsync());
}
View側のコード例:
ViewDataを使用する場合は下記のように型変換を行う必要があります。
@{
Layout = "~/Views/Shared/_JournalLayout.cshtml";
ViewData["Title"] = "Index";
IEnumerable<skyArticle> articles = ViewData["Journals"] as IEnumerable <skyArticle>;
//ViewData は、コントローラーからビューにデータを転送するために使用されます。ViewData は、文字列をキーとして使用してアクセスできる辞書オブジェクトです。
// ViewData を使用すると、コントローラーからビューに任意のオブジェクトを渡すことができます。ビューで列挙する場合は、型変換コードが必要です。
}
使用例:
<div> @foreach(var item in articles) //ViewDataの<skyArticle>を型変換されたオブジェクトarticles { <div> <img src="@item.ImageUrl" alt="..." width="100" /> </div> <div> <p>@item.Title</p> </div> } </div>
|
ViewBagを使用する場合は下記のようにforeach関数内でインスタンスを作成します。
<div> <table> <tr> <th>Id</th> <th>Code</th> <th>Name</th> </tr> @foreach (skyGenre genre in ViewBag.Genres) //ViewBag.Genresには_context.skyGenreが入っている。 //skyGenreはModelクラスのオブジェクトを指定、genreは任意名 { <tr> <td>@genre.Id</td> <td>@genre.Name</td> <td> <img src="@genre.ImageUrl" alt="..." width="100" /></td> </tr> } </table> </div> |
下図が双方の結果表示です。