タイトルから何が言いたいのかわからん
こういう作り方、すごく気持ち悪いです。
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);
}