ソースコードから理解する技術-UnderSourceCode

手を動かす(プログラムを組む)ことで技術を理解するブログ

ASP.NET MVC 2 モデルについて(2)

前回に引き続き、ASP.NET MVC 2 におけるモデルについてです。

◆モデルバインダー
ASP.NET MVCモデルバインダーを使うことで
ビュー、コントローラー間でモデルのインスタンスのやり取りを可能としています。

モデルバインダーによって
・HTML上のコントロールの表示値を、モデルのプロパティにバインドする
・コントローラー内では、(引数として渡される)モデルのプロパティを参照することで
 ビューで入力された値を取得する
ことを可能としています。

◆DefaultModelBinderクラス
先のモデルバインダーの具体的な実装を提供するのがDefaultModelBinderクラスです。
このクラスはIModelBinder インターフェイスを継承しており、.Net が扱うほとんどの型を
モデルのプロパティにバインド可能です。

バインド可能な型として、MSDNには以下の型があげられています。(※1)
・プリミティブ型(String、Double、Decimal、DateTimeなど)
・モデル クラス(つまり任意で作成したクラス)
・コレクション(ICollection、IListなど)

◆モデルバインディングの実装例
では、モデルバインディングを使用した実装の例です。
実はモデルバインディングASP.NET MVC 2 によって自動的に行われるため
DefaultModelBinderクラスについてはあまり意識してプログラミングする必要はありません。

1.下のようなデータベースからデータを取得して表示する場合
f:id:UnderSourceCode:20130504110529j:plain

2.レコードを格納するモデルを作成し・・・


public class PartyModel
{
public PartyModel(int id,
string name,
DateTime startDateTime,
DateTime endDateTime,
string place)
{
this.Id = id;
this.Name = name;
this.StartDateTime = startDateTime;
this.EndDateTime = endDateTime;
this.Place = place;
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime StartDateTime { get; set; }
public DateTime EndDateTime { get; set; }
public string Place { get; set; }
}

3.データを取得して、上のモデルに一レコードずつ格納する箇所・・・


public class PartyDAL
{
private class PartyColumns
{
public const int ID = 0;
public const int Name = 1;
public const int StartDateTime = 2;
public const int EndDateTime = 3;
public const int Place = 4;
}

public IList GetParty()
{
StringBuilder sql = new StringBuilder();
sql.Append("select ");
sql.Append(" ID, ");
sql.Append(" Name, ");
sql.Append(" StartDateTime, ");
sql.Append(" EndDateTime, ");
sql.Append(" Place ");
sql.Append("from ");
sql.Append(" Party ");

return GetParty(sql, null);
}

private IList GetParty(StringBuilder sql, SqlParameter[] parameters)
{
IList parties = new List();

using (DataAccess dataAccess = new DataAccess(System.Configuration.ConfigurationManager.ConnectionStrings["WhiskyTastingDB"].ConnectionString))
{
using (SqlDataReader reader = dataAccess.ExecuteReader(CommandType.Text, sql.ToString(), parameters))
{
while (reader.Read())
{
parties.Add(new PartyModel(reader.GetInt32(PartyColumns.ID),
reader.GetString(PartyColumns.Name),
reader.GetDateTime(PartyColumns.StartDateTime),
reader.GetDateTime(PartyColumns.EndDateTime),
reader.GetString(PartyColumns.Place)));
}
reader.Close();
}
}

return parties;
}
}

4.コントローラーは上の3.を呼び出し、取得したモデルのリストをビューに渡す・・・


public class PartyController : Controller
{
//
// GET: /Party/

public ActionResult Index()
{
IList parties = new DAL.PartyDAL().GetParty();
return View(parties);
}
}

5.ビューではforeach文で渡されたリストを一覧表示する・・・
f:id:UnderSourceCode:20130504110545j:plain

6.結果、このような一覧を表示する
f:id:UnderSourceCode:20130504110556j:plain


※1 DefaultModelBinder クラス