ASP.NETのRedirectToActionのサンプルです。VB.NETです。
目次
サンプル | 指定のクラスのアクションにリダイレクトする |
コントローラ | |
ビュー |
指定のクラスのアクションにリダイレクトする
Protected Friend Function RedirectToAction(actionName As String, controllerName As String) As RedirectToRouteResult |
RedirectToActionは、指定のアクションにリダイレクトします。Controllerクラスのメソッドです。
1つめの引数は、アクション名です。
2つめの引数は、コントローラ名です。
コントローラ
変数をセットし、別のアクションにリダイレクトするサンプルです。
Namespace Controllers
Public Class Test1Controller
Inherits Controller
<HttpGet>
Function Index() As ActionResult
Return View()
End Function
<HttpPost>
Function Action1() As ActionResult
Dim TestData As String = "テストデータ1"
TempData("p1") = TestData
Return RedirectToAction("Action2", "Test1")
End Function
<HttpGet>
Function Action2() As String
Dim str1 As String = TempData("p1")
Return str1
End Function
End Class
End Namespace
5~8行目は、初期表示で使用しています。
11行目からは、画面でボタンを押されたときに実行されます。
12行目は、文字列を変数にセットしています。
13行目は、TempDataに変数をセットしています。
Public Property TempData As TempDataDictionary |
TempDataは、ControllerBaseクラスのプロパティです。
ディクショナリなのでキーと値を保持できます。P1がキーにあたります。
14行目は、RedirectToActionで、Test1コントローラークラスのAction2アクションに移動します。
18行目は、Action2アクションです。
19行目は、TempDataから値を取得しています。
20行目は、画面に値を返します。
ビュー
@Code
Layout = Nothing
End Code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
@Using Html.BeginForm("Action1", "Test1", FormMethod.Post, New With {.id = "form1"})
@<input type="submit" id="button1" value="ボタン" />
End Using
</body>
</html>
10行目のボタンを押すと上記のコントローラの11行目から実行されます。
コントローラの20行目で出力された文字列は、画面にそのまま表示されます。
関連の記事