2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ASP.NET Core MVCモデルのビューへの値の渡し方

Posted at

ASP.NET Coreで構成するMVCアプリにおいて、コントローラーからビューにどのように値を渡せるかについてまとめました。

文字列

文字列をビューに代入して表示する。

HomeController.cs
public IActionResult About()
{
   ViewData["Message"] = "Hello World.";

   return View();
}

ViewDataに代入した値がそのまま表示されます。

about.cshtml
@{
    ViewData["Title"] = "About";
}
<p>@ViewData["Message"]</p> // Hello World.

プロパティ

ViewDataのデータ型はディクショナリーとして扱われるので、複数のプロパティやリストを格納してビューに渡すことができます。

HomeController.cs
public IActionResult Privacy()
{
   ViewData["Product"] = new Product()
   {
      Id = 1,
      Name = "Pen",
      Price = 300,
   };

  return View();
}
Privacy.cshtml
@{
    var product = ViewData["product"] as Product;
}
@product.Name // Pen

リスト

ViewDataにリストを格納した場合の例。

HomeController.cs
 List<User> nameList = new List<User>();
 foreach(var data in records)
 {
    nameList.Add(data);
 }

 ViewData["Records"] = nameList;

リストに格納された各アイテムをforeachで取り出します。

Records.cshtml
<ul>
 @foreach (var item in ViewData["Records"] as IList<User>)
 {
    <li>@item.Name</li>
 }
</ul>

参考

ASP.NET Core MVC のビュー
ViewData in ASP.NET MVC

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?