ASP.NET MVCで別のアクションページへのリンクを設置するコードを紹介します。
概要
別のアクションへのリンクを設置する場合はHTMLヘルパーのActionLinkを用います。
書式
@Html.ActionLink("(リンク文字列)", "(遷移先のアクション)")
※メソッドの引数のタイプは上記以外にも複数あります。
プログラム
コントローラーやビューの追加については「
シンプルなASP.NET MVC アプリケーションを作成する (ASP.NET MVCプログラミング)」の記事を参照してください。
コントローラー
コントローラを追加します。下記のコードを記述します。
DefaultController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ActionLinkDemo.Controllers
{
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
public ActionResult Action()
{
return View();
}
}
}
ビュー
ビューを2つ追加します。
Index.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
インデックスページです。<br/>
@Html.ActionLink("アクションページへ", "Contents")
</div>
</body>
</html>
解説
@Html.ActionLink("アクションページへ", "Action")
により、"Action"アクションへのリンクを設置します。
Action.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Send</title>
</head>
<body>
<div>
アクションページです。
</div>
</body>
</html>
実行結果
プロジェクトを実行します。 アプリケーションの /Default/Index ページを開きます。
/Default/index ページの"アクションページへ"のリンクをクリックします。別のアクションページに遷移します。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2018-07-28
作成日: 2015-02-18