How to: Customize Data Field Display in the Data Model

This topic describes how to customize the display of a data field (table column) in ASP.NET Dynamic Data by creating your own field template. The tasks described in this topic include the following:

  • Create a custom field template to customize the display of the data field.

  • Associate the custom field template with the data field. This establishes the data model connection between the data field and the custom field template.

    Note

    When you customize a data field display by using the data model, the customization applies to the entire Web site. This means that Dynamic Data uses the custom field template instead of the default template (which is selected based on the data type in the data field) used to display the data field.

This topic assumes that you have created a Dynamic Data Web Site. For information about how to create a Dynamic Data Web Site, see Walkthrough: Creating a New ASP.NET Dynamic Data Web Site Using Scaffolding. The examples in this topic use the AdventureworksLT database. For information about how to download and install the SQL Server sample database, see Microsoft SQL Server Product Samples: Database on the CodePlex site.

To create a custom field template

  1. In Solution Explorer, right-click the DynamicData/FieldTemplates folder, and then click Add New Item.

  2. Under Visual Studio installed templates, click Dynamic Data Field.

    In the Name box, enter the name of the control; you can use any name. For example, MyCustomFieldTemplate. Make sure that you select Place the code in separate file check box.

  3. Switch to or open the user control file that you just created.

  4. Create the markup that will be rendered to display the data.

    The following example shows a Label control whose Text property is set to the current field value string and whose OnDataBinding property is set to a custom event handler.

    <asp:Label id="Label1" runat="server" 
       Text='<%# FieldValueString %>'>
    </asp:Label> 
    
  5. Save and close the field template file.

  6. Open the field template code behind file to expose the partial class.

    Note

    Notice that the field template partial class is derived from the FieldTemplateUserControl class.

    partial class DynamicData_FieldTemplates_MyCustomControl: System.Web.DynamicData.FieldTemplateUserControl
    

    { }

    Public Partial Class DynamicData_FieldTemplates Inherits _ System.Web.DynamicData.FieldTemplateUserControl
    End Class 
    
  7. Customize how the field template displays the data field. For example, you can create an OnDataBinding event handler for the field template in the partial class and get the value of the current data field from the control's FieldValue property and customize how it is displayed.

    The following example shows how to handle the OnDataBinding event. For example, if the order quantity exceeds the maximum quantity allowed, the field is displayed with a red background.

    Protected override void onDataBinding(EventArgs e)
    {
            // Define the Max Quantiy that can be ordered.
            short MaxQuantity = 10;
            // Get the current number of items Ordered.
            short currentValue = (short)FieldValue;
            // Compare number ordered to the maximum quantity  
            // allowed and set the foreground color to red. 
            if (currentValue > MaxQuantity)
            {
                Label1.Forecolor = System.Drawing.Color.Red;
            }
     }
    
    Public Sub DataBindingHandler(ByVal sender As Object, ByVal e As EventArgs) 
        ' Define the Max Quantiy that can be ordered. 
        Dim MaxQuantity As Short = 10 
        ' Get the current number of items Ordered. 
        Dim currentValue As Short = CShort(FieldValue) 
        ' Compare number ordered to the maximum quantity 
        ' allowed and set the foreground color to red. 
        If currentValue < MaxQuantity Then 
            Label1.Forecolor = System.Drawing.Color.Red 
        End If 
    End Sub 
    
  8. Close the user control code behind file. You have now created a custom field template.

To associate a custom field template with a data field

  1. In Solution Explorer, right-click the App_Code folder, and then click Add New Item.

  2. Under Visual Studio installed templates, click Class.

    In the Name box, enter the name of the database table that contains the data for the custom field template to display.

    For example, if the custom field template will display data from the SalesOrderDetail table, the file name is SalesOrderDetail.cs or SalesOrderDetail.vb and the class name is SalesOrderDetail. This file will also contain an auxiliary class that lets you customize display of the data field.

  3. Switch to or open the class file that you just created.

  4. Add the Partial keyword in Visual Basic or the partial keyword in Visual C# to the class definition to make it a partial class.

  5. Add the namespace directive that refers to the System.Web.DynamicData, and System.ComponentModel.DataAnnotations, by using the Imports keyword in Visual Basic or the using keyword in Visual C#.

    using System.Web.DynamicData;
    using System.ComponentModel.DataAnnotations;
    
    Imports System.Web.DynamicData
    Imports System.ComponentModel.DataAnnotations 
    
  6. Add the MetadataTypeAttribute attribute to the partial class definition. The attribute's parameter is the name of the auxiliary metadata class that you will create in order to handle the data field display customization.

    [MetadataType(typeof(SalesOrderDetailMetadata))]
    public partial class SalesOrderDetail {
    
    }
    
    <MetadataType(GetType(SalesOrderDetailMetadata))> _
    Public Partial Class SalesOrderDetail 
    
    End Class
    
  7. Create a class that will act as the auxiliary metadata class. You can use any name for the class, but the class name must match the name that you referenced in the MetadataTypeAttribute attribute in the previous step.

  8. In the metadata class, create a field whose name corresponds to the data field to display. Mark the field by using the UIHintAttribute attribute, specifying the name of the custom field template that is used for display.

    The only purpose of the auxiliary class is to provide a place to define the UIHintAttribute attribute, so that you do not have to add any other code to the class.

    The following example shows a complete definition for the metadata class that includes a single field (with the UIHintAttribute attribute) that defines custom display for the OrderQty data field.

    public class SalesOrderDetailMetadata
    {
      [UIHint("MyCustomFieldTemplate")]
      public object OrderQty;
    }
    
    Public Class SalesOrderDetailMetadata
      <UIHint("MyCustomFieldTemplate")> _
      Public OrderQty As Object
    End Class
    

Example

The following example shows a custom field template that checks the quantity of product ordered. If the quantity ordered is greater than the maximum number allowed, the field template displays the value by using red foreground.

<%@ Control Language="vb" CodeFile="MyCustom.ascx.vb" Inherits="DynamicData_FieldTemplates_MyCustom" %>

<asp:Label id="Label1" runat="server" Text='<%# FieldValueString %>'></asp:Label> 
<%@ Control Language="C#" CodeFile="MyCustom.ascx.cs" Inherits="DynamicData_FieldTemplates_MyCustom" %>

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

Public Partial Class DynamicData_FieldTemplates_MyCustom 
    Inherits System.Web.DynamicData.FieldTemplateUserControl 





    Public Overloads Overrides ReadOnly Property DataControl() As Control 
        Get 
            Return Label1 
        End Get 
    End Property 


    Protected Overloads Overrides Sub OnDataBinding(ByVal e As EventArgs) 

        Dim MaxQuantity As Integer = 10 

        'Get the current number of items ordered 
        Dim currentValue As Short = CShort(FieldValue) 

        ' Compare the number ordered to the maximun quantity allowed and set the backgroud if the number ordered exceeds the max number allowed. 
        If currentValue > MaxQuantity Then 

            Label1.ForeColor = System.Drawing.Color.Red 
        End If 

    End Sub 


End Class 
public partial class DynamicData_FieldTemplates_MyCustom : System.Web.DynamicData.FieldTemplateUserControl 
{





    public override Control DataControl {
        get {
            return Label1;
        }
    }


    protected override void OnDataBinding(EventArgs e)
    {

            int MaxQuantity = 10;

            //Get the current number of items ordered
            short currentValue = (short)FieldValue;

            // Compare the number ordered to the maximun quantity allowed and set the backgroud if the number ordered exceeds the max number allowed.
            if (currentValue > MaxQuantity)
            {
                Label1.ForeColor = System.Drawing.Color.Red;

            }
        }


    }

<MetadataType(GetType(SalesOrderDetailMetadata))> _ 
Public Partial Class SalesOrderDetail 


End Class 

Public Class SalesOrderDetailMetadata 

   <UIHint("MyCustom")> _ 
    Public OrderQty As Object 

End Class 

[MetadataType(typeof(SalesOrderDetailMetadata))]
public partial class SalesOrderDetail
{


}


public class SalesOrderDetailMetadata
{
    [UIHint("MyCustom")]
    public Object OrderQty;

}

Compiling the Code

The following are required for compiling this code example.

  • Microsoft Visual Studio 2008 Service Pack 1 or Visual Web Developer 2008 Express Edition Service Pack 1.

  • The AdventureWorksLT sample database. For information about how to download and install the SQL Server sample database, see Microsoft SQL Server Product Samples: Database on the CodePlex site. Make sure that you install the correct version of the sample database for the version of SQL Server that you are running (Microsoft SQL Server 2005 or Microsoft SQL Server 2008).

  • A Dynamic Data Web site. This enables you to create a data context for the database and the class that contains the data field to customize and the methods to override. In addition, it creates the environment in which to use the page described before. For more information, see Walkthrough: Creating a New ASP.NET Dynamic Data Web Site Using Scaffolding.

See Also

Tasks

How to: Customize Data Field Appearance and Behavior in the Data Model

Walkthrough: Adding Dynamic Data to an Existing Web Site

Concepts

ASP.NET Dynamic Data Field Templates Overview

ASP.NET Dynamic Data Model Overview

ASP.NET Dynamic Data Overview

Change History

Date

History

Reason

July 2008

Added topic.

SP1 feature change.