0
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 5 years have passed since last update.

ASP.NET MVC5 でAction名とView名は統一すべき

Posted at

タイトルから何が言いたいのかわからん

こういう作り方、すごく気持ち悪いです。
Index2のActionからはIndex2のViewが表示されるべき。

SampleController.cs
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index()
        {
            /* なんやかんや処理 */
            return View(nameof(Index2));  // ←ActionがIndexなのにIndex2のViewが表示される
        }

        [HttpPost]
        public ActionResult Index2()
        {
            /* なんやかんや処理 */
            return View(nameof(Index3)); // ←ActionがIndex2なのにIndex3のViewが表示される
        }

Action名とView名の基本

Actionメソッドの作り方としては、以下のようにView名を省略したものが基本となる。

SampleController.cs
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

ここから例外処理や処理分岐などで表示するViewが変化することはあっても、基本的には正常時に表示されるのはIndex.cshtmlであるのが綺麗な姿である。
また、画面修正時時にurlから修正対象のViewが一発でわかるためメンテナンス性もよい。

課題

入力エラー発生時に前の画面に戻したい場合、urlとViewに差異が発生するため気持ち悪い。

SampleController.cs
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index2(SampleViewModel vm)
        {
            if (ModelState.IsValid){
                return View(nameof(Index)); // ←urlがIndex2なのにIndexのViewが表示される
            }

            new SampleModel().Register(vm);
            return View(vm);
        }

RedirectToActionを利用すればある程度回避できるが、前のActionがPostだったりすると使えなかったり、GetでもModelStateをTempData経由で持ち回る必要があったりして無理矢理感が拭えない。

SampleController.cs
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index2(SampleViewModel vm)
        {
            if (ModelState.IsValid){
                return RedirectToAction(nameof(Index));
            }

            new SampleModel().Register(vm);
            return View(vm);
        }

        [HttpPost]
        public ActionResult Index3(SampleViewModel vm)
        {
            if (ModelState.IsValid){
                TempData["ModelState"] = ModelState;
                return RedirectToAction(nameof(Index2)); // Getで定義されたActionがないのでエラー
            }

            new SampleModel().Register2(vm);
            return View(vm);
        }
0
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
0
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?