データの受け渡し
ViewDataを利用
View → Controller 同一セッション内で有効?
controller
値をセット
public ActionResult Index() {
ViewData["msg"] = "hello";
return View();
}
view
表示
<%: Html.Encode( ViewData["msg"] ) %>
クエリを利用
Controllerに値を渡す
public ActionResult Index() {
ViewData["msg"] = "hello";
return View();
}
引数を利用
View → Controller
controller
値をセット
public ActionResult Index() {
var list = new List<string>{ "value1", "value2" };
return View( list );
}
view
Inherits="System.Web.Mvc.ViewPage
表示
<% foreach (var item in Model) { %>
<%: Html.Encode( item.Imagename )%>
<br />
<% } %>
ログイン画面をつくってみる
ログイン画面をつくってみる
namespaceはMvcApplication1.Models
マスターページを使用
マスターページの作成
標準でできるものを使う感じで
Site.Master
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
</head>
<body>
<div>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
</body>
</html>
モデルの作成
public class LogOnModel {
[Required]
[DisplayName( "ユーザー名" )]
public string UserName { get; set; }
[Required]
[DataType( DataType.Password )]
[DisplayName( "パスワード" )]
public string Password { get; set; }
[DisplayName( "このアカウントを記憶する" )]
public bool RememberMe { get; set; }
}
View(ログイン画面)の作成 1
Modelの指定
ここでは「/View/Account/Logon.aspx」として作成
作成フォルダ名はコントローラ名と連動しているので重要
Modelの指定はViewの1行目にある(はず)のInheritsで指定する。
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.LogOnModel>" %>
Controllerの作成
Controllerのクラス名は「ビューのフォルダ名+Controller」で固定
今回はAccountControllerになる
Controllerのメソッド名はViewのページ(ファイル)名になる
今回はLogonになる
public class AccountController : Controller {
public ActionResult Logon() {
return View();
}
}
こんな感じ
View(ログイン画面)の作成 2
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.LogOnModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Logon
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Logon</h2>
<% using (Html.BeginForm()) { %>
<%: Html.LabelFor( m => m.UserName ) %>
<%: Html.TextBoxFor(m => m.UserName) %>
<br />
<%: Html.LabelFor(m => m.Password) %>
<%: Html.PasswordFor(m => m.Password) %> <% } %>
</asp:Content>
Html.LabelForのm.UserNameで[DisplayName( "ユーザー名" )]が利用される
多言語化をしたい場合はDisplayNameを継承したクラスを作成して利用するとかで。
Controllerの作成 2
HttpPostをつけるとPostの時に呼ばれる、戻りは引数で取得。
[HttpPost]
public ActionResult Logon( LogOnModel model ) {
return View();
}
...todo