Walkthrough: Customizing Data Field Appearance and Behavior in the Data Model

This walkthrough shows how to customize the appearance and behavior (UI) of a data field. You can perform this customization in the data layer by associating a custom field template with the data field.

Dynamic Data generates the UI for each data field by automatically selecting the appropriate field template based on the data field type. Alternatively, you can specify the custom field template to use. When you customize the UI in the data layer, the customization applies globally to a Web site—that is, the custom field template is used for all instances of the data type that you have customized.

You can also limit the customization to a single page in the presentation layer. For more information about how to choose the type of customization, see Customizing ASP.NET Dynamic Data.

In this topic you customize a data field UI by following these steps:

  • Creating two custom field templates—one to display the data and the other to provide UI to edit the data. These templates will be used by Dynamic Data to render the UI for the data field.

  • Creating a metadata partial class for the data field. This partial class represents the table that contains the data field to customize.

  • Associating the custom field templates with the data field. This instructs Dynamic Data to use the custom templates instead of the default ones when it renders the UI for the data field.

A Visual Studio project with source code is available to accompany this topic: Scaffolding Dynamic Data.

Prerequisites

Creating Custom Field Templates

To being, you will create two custom field templates, one to display data and one to render UI for editing the data. You will use these templates to customize the UI of the OrderQty data field that is contained by the SalesOrderDetail table of the AdventureWorks database.

Creating the Display Template

The template that you create in this procedure displays the data differently depending on its value. If the value is less or equal to a minimum threshold, the order quantity value is displayed in red. It the value is greater or equal to a maximum threshold, the quantity value is displayed in blue.

To create a custom field template for display

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

  2. Under Installed Templates, in the left pane, select the programming language that you prefer to work in.

  3. In the center pane, click Dynamic Data Field.

  4. In the Name box, enter a name for the custom field template. You can use any name that is not already being used by the default templates. For example, enter the name OrderQty.ascx.

  5. Make sure that the Place the code in separate file check box is selected.

  6. Click Add.

    Visual Studio creates the OrderQty.ascx and OrderQty_Edit.ascx files. The first template renders the UI for displaying the data field and the second template renders the UI for editing the data field.

  7. Open the OrderQty.ascx file.

  8. Delete the Literal control, which is part of the template that is provided by Dynamic Data.

  9. Switch to Design view.

  10. From the Standard group of the Toolbox, add a Label control to the page.

  11. In the Properties window, set the Text property of the Label control to the following expression:

    <%# FieldValueString %>
    
  12. Switch to Source view.

    The following example shows the markup for the control that you have created:

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

    This markup enables the Label control to access the value of a data field by using the FieldValueString property.

  13. Save and close the OrderQty.ascx file.

  14. Open the OrderQty.ascx.cs or OrderQty.ascx.vb class file.

  15. In the overridden DataControl method, replace the Literal1 identifier with the Label1 identifier.

    The following example shows what the code will look like when you are done.

    public override Control DataControl {
      get {return Label1;}
    }
    
    Public Overrides ReadOnly Property DataControl() As Control
      Get
        Return Label1
      End Get
    End Property
    
  16. Override the OnDataBinding method and add the following code to customize the data field display.

    protected override void OnDataBinding(EventArgs e)
    {
      // Read the quantity value.
      Int16 currentQty = (Int16)FieldValue;
      if (FieldValue != null)
      {
        // Set quantity stock thresholds.
        int min = 30;
        int max = 1500;
        if (currentQty <= min)
        {
          // Quantity is less than the minimum 
          // stock threshold.
          Label1.ForeColor = System.Drawing.Color.Red;
          Label1.Font.Bold = true;
        }
        else
          if (currentQty >= max)
          {
            // Quantity is greater than the maximum 
            // stock threshold.
            Label1.ForeColor = System.Drawing.Color.Blue;
            Label1.Font.Bold = true;
          }
      }
    }
    
    Protected Overloads Overrides Sub OnDataBinding(ByVal e As EventArgs)
      ' Read quantity value.
      Dim currentQty As Int16 = DirectCast(FieldValue, Int16)
      If FieldValue <> Nothing Then
        'Set quantity stock thresholds.
        Dim min As Integer = 30
        Dim max As Integer = 1500
        If currentQty <= min Then
          ' Quantity is less than the minimum
          ' stock threshold.
          Label1.ForeColor = System.Drawing.Color.Red
          Label1.Font.Bold = True
        ElseIf currentQty >= max Then
          ' Quantity is greater than the maximum 
          ' stock threshold.
          Label1.ForeColor = System.Drawing.Color.Blue
          Label1.Font.Bold = True
        End If
      End If
    End Sub
    

    In this method, you obtain the value of the current data field using the FieldValue property.

  17. Save and close the file.

Creating the Edit Template

In the next procedure, you create a custom field template for editing a data field. The template checks whether the value of the data field is in the allowed range. If not, the template rejects the value and displays an error.

To create a custom field template for editing

  1. Open the OrderQty_Edit.ascx file.

  2. Switch to Design view.

  3. From the Validation group of the Toolbox, add a CustomValidator control to the page.

  4. In the Properties window, set the Display property to Dynamic.

  5. Set the ControlToValidate property to TextBox1.

  6. In the Properties window toolbar, click the Events button.

  7. Set the ServerValidate property to OrderQtyValidadtion, which is the name of a custom validation handler that you will create later.

  8. Switch to Source view.

    The following example shows the markup for the control that you have created:

    <asp:CustomValidator id="CustomValidator1" runat="server" 
      ControlToValidate="TextBox1" Display="Dynamic"
      OnServerValidate="OrderQtyValidadtion" />
    
  9. Save and close the OrderQty_Edit.ascx file.

  10. Open the OrderQty.ascx_edit.cs or OrderQty.ascx_Edit.vb class file.

  11. Copy the following code into the class file in order to create a custom handler for the CustomValidator control.

    protected void OrderQtyValidation(object source, 
        ServerValidateEventArgs args)
    {
      bool result = false;
      short intUnits;
      // Convert the user's input into an integer.
      result = Int16.TryParse(TextBox1.Text, out intUnits); 
      if (result == true)
      {
        result = CheckRange(intUnits);
        // Return result.
        args.IsValid = result;
      }
      else
      {
        CustomValidator1.ErrorMessage = string.Format(
          "The value is greater than the maximum integer.");
        args.IsValid = result;
      }
    }
    
    protected bool CheckRange(int intUnits)
    {
      bool result = true;
      // Set quantity range limits.
      int min = 10;
      int max = 2000;
      // Check whether the value is in the allowed range.
      if (intUnits < min)
      {
        CustomValidator1.ErrorMessage = string.Format(
          "Value is less than the minimum threshold: {0} ", min);
           result = false;
      }
      else
        if (intUnits > max)
        {
          CustomValidator1.ErrorMessage = string.Format(
            "Value is greater than the maximum threshold: {0} ", max);
          result = false;
        }
        return result;
    }
    
    Protected Sub OrderQtyValidation(ByVal source As Object, _
      ByVal args As ServerValidateEventArgs)
      Dim result As Boolean = False
      ' Convert the user's input into an integer.
      result = Int16.TryParse(TextBox1.Text, out intUnits)
      If result = True Then
        ' Check whether the input is in the allowed range.
        result = CheckRange(intUnits)
        ' Return result.
        args.IsValid = result
      Else
        CustomValidator1.ErrorMessage = _
          String.Format("The value is greater than the maximum integer.")
        args.IsValid = result
      End If
    End Sub
    
    Protected Function CheckRange(ByVal intUnits As Integer) As Boolean
      Dim result As Boolean = True
    
      ' Set quantity range limits.
      Dim min As Integer = 10
      Dim max As Integer = 2000
    
      ' Check whether the value is in the allowed range.
      If intUnits < min Then
        CustomValidator1.ErrorMessage = _
          String.Format("Value is greater than the minimum threshold: {0} ", min)
        result = False
      ElseIf intUnits > max Then
        CustomValidator1.ErrorMessage = _
          String.Format("Value is greater than the maximum threshold: {0} ", max)
        result = False
      End If
      Return result
    End Function
    

    The handler compares the value entered by the user to predefined limits. If the user enters a value that is outside the allowed range, the code sets the text of the validator control to display an error message.

  12. Save and close the file.

Creating Metadata Classes for the Data Model

In this section, you create a partial class. This class extends the data model and enables you to associate your custom field template with a specific data field.

To create a partial class

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

  2. Under Installed Templates, in the left pane, select the programming language.

  3. In the center pane, click Class.

  4. In the Name box, enter SalesOrderDetail.cs or SalesOrderDetail.vb.

    The file name is the same as the entity class name that represents the table that contains the data field to customize. In this case the class is SalesOrderDetail. The class file that you create will also contain an associated class that lets you apply attributes to data fields.

  5. Click Add.

    Visual Studio opens the new class file.

  6. Add the Partial keyword (Visual Basic) or the partial keyword (C#) to the class definition to make it a partial class, as shown in the following example:

    public partial class SalesOrderDetail
    {
    
    }
    
    Partial Public Class SalesOrderDetail
    
    End Class 
    
  7. If you are working in C#, delete the default constructor.

  8. Import the System.Web.DynamicData and System.ComponentModel.DataAnnotations namespaces by using the Imports keyword (Visual Basic) or the using keyword (C#), as shown in the following example:

    using System.Web.DynamicData;
    using System.ComponentModel.DataAnnotations;
    
    Imports System.Web.DynamicData
    Imports System.ComponentModel.DataAnnotations 
    
  9. In the class file, add the following code in order to create another partial class that will act as the associated metadata class. You can use any name for the class.

    public partial class SalesOrderDetailMetadata
    {
    
    }
    
    Partial Public Class SalesOrderDetailMetadata
    
    End Class 
    
  10. Add the MetadataTypeAttribute attribute to the SalesOrderDetail class. Specify the name of the meta class that you just created (for example, SalesOrderDetailMetadata) as the parameter, as shown in the following example:

    [MetadataType(typeof(SalesOrderDetailMetadata))]
    public partial class SalesOrderDetail 
    {
    
    }
    
    <MetadataType(GetType(SalesOrderDetailMetadata))> _
    Partial Public Class SalesOrderDetail 
    
    End Class
    

    The attribute associates the partial SalesOrderDetail class with the SalesOrderDetailMetadata metadata class.

  11. Save the file, but do not close it.

Associating the Custom Field Template with a Data Field

In this section, you will associate the custom field template that you have created with a data field in the data layer. After you have made this association, Dynamic Data will use your custom templates instead of the default ones when it renders the UI for the data field.

To associate the custom field template with a data field

  1. In the metadata class, create a public property named OrderQty (which matches the data field that you want to customize), as shown in the following example:

    public partial class SalesOrderDetailMetadata
    {    
      public object OrderQty;
    }
    
    Partial Public Class SalesOrderDetailMetadata
      Public OrderQty As Object
    End Class 
    

    The Object type is used as a placeholder to represent the data field. Dynamic Data infers the actual type from the data model at run time.

  2. Add the UIHintAttribute attribute to the property and specify the name of the custom field template (OrderQty) to use, as shown in the following example:

    public partial class SalesOrderDetailMetadata
    {    
    [UIHint("OrderQty")]
      public object OrderQty;
    }
    
    Partial Public Class SalesOrderDetailMetadata
    <UIHint("OrderQty")> _
      Public OrderQty As Object
    End Class 
    
  3. Save and close the file.

Testing Data Field Customization

You can now test the following custom template behavior:

  • The custom template is used when you display or edit values in the OrderQty field.

  • The OrderQty.ascx field template displays its value in red if the OrderQty value is less or equal to the minimum stock threshold. It displays the value in blue if the value is greater or equal to the maximum stock threshold.

  • The OrderQty_Edit.ascx field template checks the OrderQty value entered by the user against absolute range limits. A custom error message is displayed if the value entered by the user is not in the allowed range.

To test data field customization

  1. In Solution Explorer, right-click the Default.aspx page and select View in Browser.

  2. In the displayed table list, click the SalesOrderDetails link.

    Dynamic Data displays the SalesOrderDetail table by using the custom field template that you have created.

  3. In any row, click Edit.

  4. For the OrderQty column, enter a value that is less than the minimum stock threshold (30), such as 25.

  5. In the same row, click Update.

    Dynamic Data displays the value that you entered in red. This means that the value is less than the minimum stock threshold.

  6. In any row, click Edit.

  7. For the OrderQty column, enter a value that is greater than the minimum stock threshold but less than the maximum stock threshold (1500), such as 250.

  8. In the same row, click Update.

    Dynamic Data displays the value in the default color. This means that the value is in the stock threshold range.

  9. In any row, click Edit.

  10. For the OrderQty column, enter a value that is greater than the maximum stock threshold (1500), such as 1800.

  11. On the same row, click Update.

    Dynamic Data displays the value in blue. This means that the value is greater than the stock threshold.

  12. In any row, click Edit.

  13. For the OrderQty column, enter a value that is less than the minimum value (10), such as 5.

  14. In the same row, click Update.

    Dynamic Data displays an error message that states that the value entered is less than the minimum value.

  15. Click Cancel.

  16. In any row, click Edit.

  17. For the OrderQty column, enter a value that is greater than the maximum value (2000), such as 2800.

  18. In the same row, click Update.

    Dynamic Data displays an error message that states that the value entered is greater than the maximum value.

  19. On the same row, click Cancel.

Next Steps

This walkthrough has illustrated the basic principles of how to customize Dynamic Data in the data layer by using a custom field template. Suggestions for additional exploration include the following:

See Also

Tasks

Walkthrough: Adding Dynamic Data Scaffolding to Existing ASP.NET Web Sites

Reference

FieldTemplateUserControl

UIHintAttribute