The following example shows how to use the RangeAttribute to customize formatting for a data field. The example performs the following steps:
Implements a metadata partial class and the associated metadata class.
In the associated metadata class, it applies the RangeAttribute attribute to obtain the following results:
Apply the attribute to a data field of type integer.
Apply the attribute to an integer data field and define a custom validation error message.
Apply the attribute to a DateTime data field and define a custom validation error message.
Imports System
Imports System.Web.DynamicData
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel
<MetadataType(GetType(ProductMetaData))> _
Partial Public Class Product
End Class
Public Class ProductMetaData
<Range(10, 1000, _
ErrorMessage:="Value for {0} must be between {1} and {2}.")> _
Public Weight As Object
<Range(300, 3000)> _
Public ListPrice As Object
<Range(GetType(DateTime), "1/2/2004", "3/4/2004", _
ErrorMessage:="Value for {0} must be between {1} and {2}")> _
Public SellEndDate As Object
End Class
using System;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
[MetadataType(typeof(ProductMetaData))]
public partial class Product
{
}
public class ProductMetaData
{
[Range(10, 1000,
ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public object Weight;
[Range(300, 3000)]
public object ListPrice;
[Range(typeof(DateTime), "1/2/2004", "3/4/2004",
ErrorMessage = "Value for {0} must be between {1} and {2}")]
public object SellEndDate;
}
To compile the example, you need the following:
Visual Studio 2008 Service Pack 1 or Visual 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 (SQL Server 2005 or SQL Server 2008).
A data-driven Web site. This enables you to create a data context for the database and the class that contains the data field to customize. For more information, see Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding.