3
3

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.

強く型指定されたViewModelをビューに渡す

Last updated at Posted at 2021-08-07

はじめに

Microsoftの公式解説書『プログラミング ASP.NET Core』を読んで強く型指定を行った上でビューにデータを渡す方法を知ったので備忘録としてまとめたいと思います。

今までViewDataやViewBagを利用していた

恥ずかしながら今まではViewDataやViewBagを利用してControllerからViewへデータを渡す方法しか知りませんでした。
こんな感じ↓

TestController.cs
public IActionResult Create([Bind("Title,Number")] Test test)
{
    ViewData["Title"] = test.Title;
    ViewData["Number"] = test.Number;
    return View(test);
}

便利ではあるのですがViewDataのキー(上記のコードでいうと"Title"や"Number")をtypoして実行時エラーを出したり、(ViewBagなどで)インテリジェンスがなくて効率が落ちるたびに「ぐぬぬ。。。」と思っていました。

ViewModelを作成してビューに渡す

そこでViewModelを作成してビューにデータを渡していきます。

具体的にASP.NET Core MVCを利用して書いていこうと思います。
VisualStudio 2019を立ち上げて『新しいプロジェクトの作成』>『ASP.NET Core Webアプリ(Model-View-Controller)』を起動します。
ビルドして実行すると以下の画面になるかと思いますが、以下の赤枠部分をテキトーに「Test」と変えてみましょう。
1.png

今までの僕だとこんな感じで書いていたでしょう。

HomeController.cs
public IActionResult Index()
{
    ViewData["Name"] = "Test";
    return View();
}
Index.cshtml
<div class="text-center">
    <h1 class="display-4">@ViewData["Name"]</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

それを・・・ViewModelを用いるとこんな感じ。
Modelフォルダ内にViewModelフォルダを作成し、HomeViewModel.csを新規作成しています。

HomeViewModel.cs
public sealed class HomeViewModel
{
    public string Name { get; set; }
}
HomeController.cs
public IActionResult Index()
{
    var viewModel = new HomeViewModel()
    {
        Name = "Test"
    };
    return View(viewModel);
}
Index.cshtml
@model WebApplication1.Models.ViewModels.HomeViewModel
<div class="text-center">
    <h1 class="display-4">@Model.Name</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

実行結果↓
2.png

ちゃんと変更できましたね!
これなら型が異なっていた際にも実行前にビルドエラーで気づけますし、Viewではインテリジェンスが効いてより書きやすくなります。

おわりに

もちろんViewDataやViewBagを利用するのは悪いことではありません。
最初に取り上げたMicrosoftの公式解説書『プログラミング ASP.NET Core』でも手っ取り早く実装できる利点があると書かれていますし、実際のところ確かにその通りです。
ただし大きなアプリを作る際にはやはり保守性が微妙になってくるのでViewModelを用いる設計を基本としていきましょ~!

3
3
1

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?