次の方法で共有


方法 : データ モデルでデータ フィールドの表示をカスタマイズする

更新 : 2007 年 11 月

このトピックでは、独自のフィールド テンプレートを作成することにより、ASP.NET Dynamic Data でデータ フィールド (テーブルの列) の表示をカスタマイズする方法を紹介します。ここでは、次のタスクについて説明します。

  • カスタム フィールド テンプレートを作成して、データ フィールドの表示をカスタマイズする。

  • カスタム フィールド テンプレートとデータ フィールドを関連付ける。これにより、データ フィールドと、表示処理用のカスタム フィールド テンプレートとの間にデータ モデル接続が確立されます。

    Cc488522.alert_note(ja-jp,VS.90).gifメモ :

    データ モデルを使用してデータ フィールドの表示をカスタマイズすると、そのカスタマイズが Web サイト全体に適用されます。つまり、Dynamic Data は、データ フィールドの型に基づいて既定のテンプレートを選択するのではなく、カスタム フィールド テンプレートを使用してデータ フィールドを表示するようになります。

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

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

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

    [名前] ボックスにコントロールの名前を入力します。任意の名前を使用できます。[別のファイルにコードを書き込む] ボックスがオンになっていることを確認します。

  3. 作成したユーザー コントロール ファイルに切り替えるか、そのファイルを開きます。

  4. @ Control ディレクティブに、分離コード ファイルを参照する CodeFile 属性と、コントロール クラスを参照する Inherits 属性を追加します。

    <%@ Control Language="C#" 
      CodeFile=MyCustomControl.ascx.cs"
      Inherits="MyCustomControl" %>
    
    <%@ Control Language="VB" 
      CodeFile=MyCustomControl.ascx.cs"
      Inherits="MyCustomControl" %>
    
  5. データを表示する際にレンダリングされるマークアップを作成します。

    Label コントロールの例を以下に示します。Text プロパティには現在のフィールド値の文字列を設定し、OnDataBinding プロパティにはカスタム イベント ハンドラを設定しています。

    <asp:Label id="TextLabel1" runat="server" 
      OnDataBinding="DataBindingHandler" 
      Text='<%# FieldValueString %>'>
    </asp:Label> 
    
  6. ユーザー コントロール ファイルを保存して閉じます。

  7. ユーザー コントロールの分離コード ファイルを開きます。

  8. Imports キーワード (Visual Basic の場合) または using キーワード (Visual C# の場合) を使用して、System.Web.DynamicData を参照する名前空間ディレクティブを追加します。

    using System.Web.DynamicData;
    
    Imports System.Web.DynamicData
    
  9. 次のように、FieldTemplateUserControl クラスからユーザー コントロールの部分クラスを派生します。

    partial class MyCustomControl: FieldTemplateUserControl
    

    { }

    Public Partial Class MyCustomControl Inherits _ FieldTemplateUserControl
    
    End Class 
    
  10. コントロールによるデータ フィールドの表示をカスタマイズするには、ユーザー コントロールの OnDataBinding イベントを処理します。ハンドラでは、コントロールの FieldValue プロパティから現在のデータ フィールドの値を取得できます。この値を使用して表示をカスタマイズできます。

    OnDataBinding イベントを処理する方法を次の例に示します。

    public void DataBindingHandler(object sender, EventArgs e)
    {
      // Define the understocked threshold.
      short underStockedThreshold = 150;
      // Get the current number of items in stock.
      short currentValue = (short)FieldValue;
      // Check product stock. 
      if (currentValue < underStockedThreshold)
      {
          // Customize display here. For example you show the data with      
         //a red background.
      }
    }
    
    Public Sub DataBindingHandler(ByVal sender As Object, _
    ByVal e As EventArgs)
      ' Define the understocked threshold.
      Dim underStockedThreshold As Short = 150
      ' Get the current number of items in stock.
        Dim currentValue As Short = DirectCast(FieldValue, Short)
        ' Check product stock. 
        If currentValue < underStockedThreshold Then
            'Customize display here. For example you show the data with      
           'a red background.
        End If
    End Sub
    
  11. ユーザー コントロールの分離コード ファイルを閉じます。これで、カスタム フィールド テンプレートの作成は完了です。

カスタム フィールド テンプレートとデータ フィールドを関連付けるには

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

  2. [インストールされているテンプレート][クラス] をクリックします。

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

    たとえば、Products テーブルのデータを表示するカスタム コントロールの場合、ファイル名は Products.cs または Product.vb に、クラス名は Product になります。このファイルには、データ フィールドの表示をカスタマイズするための補助クラスも格納されます。

  3. 作成したクラス ファイルに切り替えるか、そのファイルを開きます。

  4. クラス定義に Partial キーワード (Visual Basic の場合) または partial キーワード (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. 部分クラス定義に MetadataTypeAttribute 属性を追加します。この属性のパラメータは、データ フィールドの表示のカスタマイズを処理するために後で作成する補助的なメタデータ クラスの名前です。

    [MetadataType(typeof(ProductMetadata))]
    public partial class Product {
    
    }
    
    <MetadataType(GetType(ProductMetadata))> _
    Public Partial Class Product 
    
    End Class
    
  7. 補助的なメタデータ クラスとして機能するクラスを作成します。このクラスには任意の名前を使用できますが、前の手順の MetadataTypeAttribute 属性で参照した名前に合わせる必要があります。

  8. メタデータ クラスに、表示するデータ フィールドに対応する名前のフィールドを作成します。このフィールドを UIHintAttribute 属性でマークし、表示に使用するカスタム フィールド テンプレートの名前を指定します。

    この補助クラスは、UIHintAttribute 属性を定義するためだけに使用されます。他にコードを追加する必要はありません。

    次の例は、メタデータ クラスの完全な定義を示しています。このメタデータ クラスには、UnitsInStock フィールドのカスタム表示を定義する単一のフィールド (UIHintAttribute 属性が指定されている) が含まれます。

    public class ProductMetadata
      [UIHint("UnitsInStock")]
      public object UnitsInStock;
    }
    
    Public Class ProductMetadata 
      <UIHint("UnitsInStock")> _
      Public UnitsInStock As Object
    End Class
    

使用例

製品の在庫レベルをチェックするカスタム フィールド テンプレートを次の例に示します。製品の在庫が不足すると、値が赤色の前景色で表示されます。

<%@ Control Language="VB" CodeFile="UnitsInStock.ascx.vb" 
Inherits="DynamicData_FieldTemplates_UnitsInStock" %>

<asp:Label id="TextLabel1" OnDataBinding="DataBindingHandler"
Text='<%# FieldValueString %>' runat="server"></asp:Label>

<%@ Control Language="C#" CodeFile="UnitsInStock.ascx.cs" 
Inherits="DynamicData_FieldTemplates_UnitsInStock" %>

<asp:Label id="TextLabel1" OnDataBinding="DataBindingHandler"
Text='<%# FieldValueString %>' runat="server"></asp:Label>

Imports System.Web.DynamicData

Partial Public Class DynamicData_FieldTemplates_UnitsInStock
    Inherits FieldTemplateUserControl
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

    End Sub

    ' DataBinding event handler.
    Public Sub DataBindingHandler(ByVal sender As Object, _
                                  ByVal e As EventArgs)
        ' Define product understocked threshold.
        Dim underStockedThreshold As Short = 150

        ' Get the current number of items in stock.
        Dim currentValue As Short = DirectCast(FieldValue, Short)

        ' Check product stock. 
        If currentValue < underStockedThreshold Then
            ' The product is understocked, set its 
            ' foreground color to red.
            TextLabel1.ForeColor = System.Drawing.Color.Red
        End If
    End Sub

End Class
using System.Web.DynamicData;

public partial class DynamicData_FieldTemplates_UnitsInStock :  FieldTemplateUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    // DataBinding event handler.
    public void DataBindingHandler(object sender, EventArgs e)
    {
        // Define product understocked threshold.
        short underStockedThreshold = 150;

        // Get the current number of items in stock.
        short currentValue = (short)FieldValue;

        // Check product stock. 
        if (currentValue < underStockedThreshold)
        {
            // The product is understocked, set its 
            // foreground color to red.
            TextLabel1.ForeColor = System.Drawing.Color.Red;
        }
    }

}

コードのコンパイル方法

  • 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) に対応した正しいバージョンのサンプル データベースをインストールしてください。

  • Dynamic Data Web サイト。これにより、データベースのコンテキストと、カスタマイズするデータ フィールドおよびオーバーライドするメソッドを持つクラスを作成できます。また、前に説明したページを使用するための環境も作成されます。詳細については、「チュートリアル : スキャフォールディングを使用した新しい Dynamic Data Web サイトの作成」を参照してください。

参照

処理手順

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

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

概念

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

ASP.NET Dynamic Data モデルの概要

ASP.NET Dynamic Data の概要