方法 : データ モデルのデータ フィールドの外観と動作をカスタマイズする

更新 : 2007 年 11 月

ASP.NET Dynamic Data には、データ フィールドの表示および編集のための UI を表示するフィールド テンプレートが含まれています。既存のフィールド テンプレートを変更したり、新しいカスタム フィールド テンプレートを作成したりすることで、UI をカスタマイズできます。

ここでは、次の手順に従ってデータ フィールドの外観および動作をカスタマイズする方法について説明します。

  • UIHintAttribute 属性をデータ モデルのデータ フィールドに適用する。これにより、特定のカスタム フィールド テンプレートを使用してデータ フィールドを処理するように Dynamic Data に指示します。

  • 対応するカスタム フィールド テンプレートを作成して、データ フィールドの表示および編集を行うための UI を表示する。

このトピックで説明しているように、データ層のデータ フィールドをカスタマイズすると、カスタマイズが Web サイトに対してグローバルに適用されます。この場合、Dynamic Data は、組み込みのテンプレート (データ フィールドの組み込み型に基づいて選択される) の代わりに、カスタム フィールド テンプレートを使用して、データ フィールドの表示と変更を行います。

または、カスタマイズを 1 つのページに制限することもできます。詳細については、「方法 : カスタム ページ テンプレートを使用して個々のテーブルのレイアウトをカスタマイズする」を参照してください。

データ層のデータ フィールドをカスタマイズするには、いくつかの手順を実行する必要があります。このトピックの手順は、プロセスの各ステップを示しています。

この機能のオンライン サンプルを実行してください。

データ モデルのカスタム フィールド テンプレートの指定

このセクションでは、カスタム フィールド テンプレートをデータ フィールドに関連付ける手順について説明します。

属性をデータ フィールドに適用するには

  1. ソリューション エクスプローラで、App_Code フォルダを右クリックし、[新しい項目の追加] をクリックします。

  2. [Visual Studio にインストールされたテンプレート][クラス] をクリックします。

  3. [名前] ボックスに、カスタム フィールド テンプレートで表示するデータが格納されたデータベース テーブルの名前 (データ モデルで定義されている名前) を入力します。

    ファイル名は、テーブルを表すエンティティ クラス名にする必要があります。たとえば、カスタム フィールド テンプレートで SalesOrderDetail テーブルのデータを表示する場合、ファイル名は SalesOrderDetail.cs または SalesOrderDetail.vb に、クラス名は SalesOrderDetail になります。作成したクラス ファイルには、データ フィールドに属性を適用するための関連付けられたクラスも格納されます。

  4. Partial キーワード (Visual Basic の場合)、または partial キーワード (Visual C# の場合) をクラス定義に追加して部分クラスにします。Visual C# で作業する場合は、既定のコンストラクタを削除します。

  5. Imports キーワード (Visual Basic の場合) または using キーワード (Visual C# の場合) を使用して、System.Web.DynamicData 名前空間と System.ComponentModel.DataAnnotations 名前空間をインポートします。次に例を示します。

    using System.Web.DynamicData;
    using System.ComponentModel.DataAnnotations;
    
    Imports System.Web.DynamicData
    Imports System.ComponentModel.DataAnnotations 
    
  6. 手順 1. ~ 3. で作成したクラス ファイルで、関連メタデータ クラスとして動作する別の部分クラスを作成します。クラス名には、任意の名前を使用できます。

    次の例では、SalesOrderDetail フィールドの関連メタデータ クラスを作成しています。

    public partial class SalesOrderDetailMetadata
    {
    
    }
    
    Partial Public Class SalesOrderDetailMetadata
    
    End Class 
    
  7. データ テーブルの部分クラス定義に MetadataTypeAttribute 属性を追加します。属性のパラメータには、前の手順で作成した関連メタデータ クラスの名前を指定します。

    次の例では、SalesOrderDetail 部分クラスを関連メタデータ クラスに接続する属性を適用しています。

    [MetadataType(typeof(SalesOrderDetailMetadata))]
    public partial class SalesOrderDetail 
    {
    
    }
    
    <MetadataType(GetType(SalesOrderDetailMetadata))> _
    Partial Public Class SalesOrderDetail 
    
    End Class
    
  8. 関連メタデータ クラスで、カスタマイズするデータ フィールドに一致する名前を持つ、パブリック プロパティを作成します。

  9. UIHintAttribute 属性をプロパティに適用し、表示および編集に使用するカスタム フィールド テンプレートの名前を指定します。

    Object 型は、データ フィールドを表すメタデータ クラスのプレースホルダ型として使用されます。Dynamic Data は、実行時にデータ モデルから実際の型を推論します。

    public partial class SalesOrderDetailMetadata
    {    
        [UIHint("CustomFieldTemplate")]
        public object OrderQty;
    }
    
    Partial Public Class SalesOrderDetailMetadata
        <UIHint("CustomFieldTemplate")> _
        Public OrderQty As Object
    End Class 
    
  10. クラス ファイルを保存して、閉じます。

カスタム フィールド テンプレートの作成

フィールド テンプレートは、Dynamic Data でデータ フィールドを表示および編集するための UI の表示に使用されるユーザー コントロールです。このセクションでは、データ フィールドを表示するための UI を表示する、カスタム フィールド テンプレートを作成する手順について説明します。

表示用のカスタム フィールド テンプレートを作成するには

  1. ソリューション エクスプローラで、DynamicData/FieldTemplates フォルダを右クリックし、[新しい項目の追加] をクリックします。

  2. [Visual Studio にインストールされたテンプレート][Dynamic Data フィールド] をクリックします。

  3. [名前] ボックスに、カスタム フィールド テンプレートの名前を入力します。まだ使用されていない任意の名前を使用できます。[別のファイルにコードを書き込む] ボックスがオンになっていることを確認します。

  4. [追加] をクリックします。

    Visual Studio によってフィールド テンプレートが 2 つ作成されます。1 つは表示用、もう 1 つは編集用です。たとえば、入力した名前が CustomFieldTemplate.ascx である場合、Visual Studio によって CustomFieldTemplate.ascx と CustomFieldTemplate_Edit.ascx が作成されます。最初のテンプレートはデータ フィールドを表示するための UI をレンダリングし、2 つ目のテンプレートはデータ フィールドを編集するための UI をレンダリングします。

  5. データ フィールドの表示をカスタマイズする場合は、表示用のユーザー コントロール ファイルを開き、カスタマイズを追加します。

    データ表示用にカスタマイズされたフィールド テンプレートを次の例に示します。この例では、Dynamic Data フィールド テンプレートに既定で用意されている Literal コントロールは、Text プロパティが現在のフィールド値の文字列に設定された Label コントロールで置き換えられます。FieldValueString プロパティを使用して、データ フィールドの値にアクセスできます。

    <asp:Label id="Label1" runat="server" 
      Text='<%# FieldValueString %>'>
    </asp:Label> 
    
  6. カスタマイズに必要な場合は、表示用のフィールド テンプレートの分離コード ファイルを開き、カスタマイズを追加します。

    次の例では、前の手順のマークアップでの変更にコードを同期させています。このコードでは、Literal1 識別子を Label1 識別子で置き換えて、表示用の UI のカスタマイズをサポートしています。

    public override Control DataControl {
      get {return Label1;}
    }
    
    Public Overrides ReadOnly Property DataControl() As Control
      Get
        Return Label1
      End Get
    End Property
    
  7. フィールド テンプレートの OnDataBinding メソッドをオーバーライドし、データ フィールドの表示をカスタマイズするコードを追加します。

    次の例に示すように、このメソッドでコントロールの FieldValue プロパティから現在のデータ フィールドの値を取得することによって、表示をカスタマイズできます。

    protected override void OnDataBinding(EventArgs e)
    {
    
        if (currentQty < min)
        {
          Label1.ForeColor = System.Drawing.Color.Red;
          Label1.Font.Bold = true;
        }
        else
          if (currentQty > max)
          {
            Label1.ForeColor = System.Drawing.Color.Blue;
            Label1.Font.Bold = true;
           }
        }
      }
    
    Protected Overloads Overrides Sub OnDataBinding( _
    ByVal e As EventArgs)
    
        If currentQty < min Then
          Label1.ForeColor = System.Drawing.Color.Red
          Label1.Font.Bold = True
        ElseIf currentQty > max Then
          Label1.ForeColor = System.Drawing.Color.Blue
          Label1.Font.Bold = True
        End If
      End If
    End Sub 
    

次の手順では、データ フィールドを編集するための UI を表示するカスタム フィールド テンプレートを作成する手順について説明します。

編集用のカスタム フィールド テンプレートを作成するには

  1. 名前の末尾に _Edit サフィックスが付加されているカスタム フィールド テンプレートを開き、カスタマイズを追加します。

    次の例では、ユーザーによって入力されたデータが無効な場合にカスタム警告メッセージを表示する、CustomValidator コントロール (全般リファレンス) コントロールを追加するマークアップを示しています。たとえば、データ フィールド値が、フィールド テンプレートに定義された特定の範囲外である場合にメッセージが表示されます。この例では、検証が失敗した場合にのみ検証コントロールが表示されるように、検証コントロールの Display プロパティに "Dynamic" を設定しています。このコードでは、コントロールの ID に ControlToValidate 属性を設定して検証を行います。また、検証イベントのハンドラの名前に OnServerValidate 属性を設定します。

    <asp:CustomValidator id="CustomValidator1" runat="server" 
      ControlToValidate="TextBox1" Display="Dynamic"
      OnServerValidate="CustomValidation" />
    
  2. ユーザー コントロール ファイルを保存して閉じます。

  3. カスタマイズに必要な場合は、編集用のフィールド テンプレートの分離コード ファイルを開き、カスタマイズを追加します。

    次の例では、CustomValidator コントロールのサーバー コードを作成しています。このコードでは、ユーザーにより入力された値としきい値を比較し、データが許容される範囲内の値でない場合にエラー メッセージを表示します。

    protected void CustomValidation(object source, 
       ServerValidateEventArgs args)
    {
        // Check if the input is in the allowed range.
        bool result = CheckRange(intUnits);
        // Return result.    
        args.IsValid = result;
    }
    
    Protected Sub CustomValidation( _
      ByVal source As Object, ByVal args As ServerValidateEventArgs)
    
        'Check if the value is in the allowed range.
         Dim result As Boolean = CheckRange(intUnits)
         'Return result.    
         args.IsValid = result
    End Sub
    

使用例

この例では、データ モデルを使用して、SalesOrderDetail テーブルの OrderQty データ フィールドの表示および編集用に表示される UI をカスタマイズしています。

CustomFieldTemplate.ascx フィールド テンプレートは、注文数が最小の警告しきい値よりも小さい場合に、赤の前景を使用してその値を表示します。注文数が最大警告しきい値よりも大きい場合には、青の前景を使用してその値を表示します。

CustomFieldTemplate_Edit.ascx フィールド テンプレートは、ユーザーによって入力された OrderQty 値について範囲の制限をチェックします。ユーザーによって入力された値が許容範囲外である場合に、カスタム エラー メッセージが表示されます。

<%@ Page Language="VB" 
AutoEventWireup="true" CodeFile="CustomAppearanceBehavior.aspx.vb" 
Inherits="CustomAppearanceBehavior" %>


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <link href="~/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
     <h2>Example: <%=Title%></h2>

     <!-- Enable dynamic behavior. The GridView must be 
     registered with the manager. See code-behind file. -->
    <asp:DynamicDataManager ID="DynamicDataManager1" runat="server"
        AutoLoadForeignKeys="true" />


    <form id="form1" runat="server">

        <!-- Capture validation exceptions -->
        <asp:DynamicValidator ID="ValidatorID" ControlToValidate="GridView1" 
            runat="server" /> 

        <asp:GridView ID="GridView1" 
            runat="server" 
            DataSourceID="GridDataSource" 
            AutoGenerateColumns="false"  
            AutoGenerateEditButton="true"
            AllowPaging="true"
            PageSize="10"
            AllowSorting="true">
            <Columns>
                <asp:DynamicField DataField="OrderQty" />
                <asp:DynamicField DataField="UnitPrice" />
                <asp:DynamicField DataField="ModifiedDate" />
            </Columns>
            <EmptyDataTemplate>
                There are currently no items in this table.
            </EmptyDataTemplate>
       </asp:GridView>
    </form>

    <!-- Connect to the database -->
    <asp:LinqDataSource ID="GridDataSource" runat="server"  
        TableName="SalesOrderDetails" EnableUpdate="true"
        ContextTypeName="AdventureWorksLTDataContext">
    </asp:LinqDataSource>
</body>
</html>
<%@ Page Language="C#" 
AutoEventWireup="true" CodeFile="CustomAppearanceBehavior.aspx.cs" 
Inherits="CustomAppearanceBehavior" %>


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <link href="~/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
     <h2>Example: <%=Title%></h2>

     <!-- Enable dynamic behavior. The GridView must be 
     registered with the manager. See code-behind file. -->
    <asp:DynamicDataManager ID="DynamicDataManager1" runat="server"
        AutoLoadForeignKeys="true" />


    <form id="form1" runat="server">

        <!-- Capture validation exceptions -->
        <asp:DynamicValidator ID="ValidatorID" ControlToValidate="GridView1" 
            runat="server" /> 

        <asp:GridView ID="GridView1" 
            runat="server" 
            DataSourceID="GridDataSource" 
            AutoGenerateColumns="false"  
            AutoGenerateEditButton="true"
            AllowPaging="true"
            PageSize="10"
            AllowSorting="true">
            <Columns>
                <asp:DynamicField DataField="OrderQty" />
                <asp:DynamicField DataField="UnitPrice" />
                <asp:DynamicField DataField="ModifiedDate" />
            </Columns>
            <EmptyDataTemplate>
                There are currently no items in this table.
            </EmptyDataTemplate>
       </asp:GridView>
    </form>

    <!-- Connect to the database -->
    <asp:LinqDataSource ID="GridDataSource" runat="server"  
        TableName="SalesOrderDetails" EnableUpdate="true"
        ContextTypeName="AdventureWorksLTDataContext">
    </asp:LinqDataSource>
</body>
</html>
Imports System
Imports System.Collections
Imports System.Configuration
Imports System.Web.DynamicData

Partial Public Class CustomAppearanceBehavior
    Inherits System.Web.UI.Page
    Protected _table As MetaTable

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
        ' Register control with the data manager.
        DynamicDataManager1.RegisterControl(GridView1)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        ' Get the table entity.
        _table = GridDataSource.GetTable()

        ' Assign title dynamically.
        Title = String.Concat( _
        "Customize Appearance and Behavior of the ", _
        _table.Columns(2).DisplayName, " Data Field")
    End Sub
End Class
using System;
using System.Collections;
using System.Configuration;
using System.Web.DynamicData;

public partial class CustomAppearanceBehavior : System.Web.UI.Page
{
    protected MetaTable _table;

    protected void Page_Init(object sender, EventArgs e)
    {
        // Register control with the data manager.
        DynamicDataManager1.RegisterControl(GridView1);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Get the table entity.
        _table = GridDataSource.GetTable();

        // Assign title dynamically.

        Title = string.Concat("Customize Appearance and Behavior of the ",
            _table.Columns[2].DisplayName, " Data Field");

    }
}

コードのコンパイル方法

このコード例をコンパイルするには、以下が必要です。

  • Microsoft Visual Studio 2008 Service Pack 1 または Visual Web Developer 2008 Express Edition Service Pack 1。

  • AdventureWorksLT サンプル データベース。SQL Server のサンプル データベースをダウンロードしてインストールする方法については、CodePlex サイトの「Microsoft SQL Server Product Samples: Database」を参照してください。実行している SQL Server のバージョン (Microsoft SQL Server 2005 または Microsoft SQL Server 2008) に対応した正しいバージョンのサンプル データベースをインストールしてください。

  • 動的なデータ ドリブン Web サイト。これにより、データベースのデータ コンテキストと、カスタマイズするデータ フィールドを持つクラスを作成できます。詳細については、「Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding」を参照してください。

参照

処理手順

チュートリアル : 既存の Web サイトへの Dynamic Data の追加

概念

ASP.NET Dynamic Data のフィールド テンプレートの概要

ASP.NET Dynamic Data モデルの概要

ASP.NET Dynamic Data の概要

参照

FieldTemplateUserControl