Dynamic Data Templates in ASP.NET 3.5

Gayani gives an introduction to Dynamic Data Templates in ASP.NET 3.5 and explains how one can save a great deal of time and effort when building data-driven web sites by using them



Developers regularly waste (or should I say lose) huge amounts of their time when building up data-driven web applications by going through the same repetitive tasks each and every time. Whilst the database varies from one application to the next, the applications themselves share similar features which need to be duplicated, such as querying the database and presenting data. In a bid to help those developers reclaim their hours, Microsoft introduced the Dynamic Data Templates with the release of Visual Studio 2008.

At a high level, Dynamic Data Templates can be seen as a system to very quickly build up a User Interface linked with the relevant data model, immediately enabling you to perform CRUD  operations (Create, Read, Update, Delete) on the database using the specified data source. They provide a powerful method for building up these kinds of applications, and I’m going to focus on an overview of what Dynamic Data Templates actually are, and a few ways of customizing them to suit industry needs.

Creating a Dynamic Data Website


The first step in building your application is applying the Dynamic Data Website template to your ASP.NET application. This makes a set of folders available which contain pages, user controls and templates – everything you’ll need to make the magic happen, as we’ll see in a moment.

(This template uses the LINQ to SQL data model and LINQ datasource. To use the ADO.NET Entity data model you need to add the Dynamic Data Entities template instead. )

Secondly, to formulate the data layer of our ASP.NET application, you’ll need to add a data model (I’ve used AdventureWKS ) using the LINQ to SQL class. The AdventureWKS data model has the following class repres­ent­ations of tables from the Adventure Works database:


To map the templates onto the database, we need to register the data model and specify the routing technique by editing Global.asax as follows.

The RegisterRoutes method uses a MetaModel object to enable the Scaffolding framework, which is what makes the DDT so powerful. This MetaModel object allows the templates to dynamically create the URL patterms which process the CRUD requests. So, in addition to registering the data model, we’ll also need to specify the DataContext type and the ScaffoldAllTables property. This will ensure that the whole data model exhibits the Dynamic Data functionality.

Lastly, we need to add a new Route to the routes collection by specifing the URL pattern and the model we just registered.

After these steps, we have a fully-functional application ready to run.


The elements of the data model are now linked, making the CRUD operations possible. It’s also important to appreciate that these relationships are automatically represented correctly, and the controls are all rendered appropriately according to field type. (e.g. Boolean values appear as checkboxes in edit mode).

Not only does this basic setup enable CRUD operations, it also uses foreign key relationships to provide filtering, sorting and paging operations. An easy example of this kind of functionality can be seen by following the ‘View ProductVendors‘ link. The application also has customizable field validation functionality which can be seen in the Edit pages, and can be tweaked to control required fields, as well as the format of field content; I’ll come back to this a little later.


Underlying Mechanism

Use of URL Routing and Page Templates

Dynamic Data Templates use the ASP.NET Routing technique to construct URL patterns dynamically, using parameterized information to call appropriate templates and automatically populate them rather than relying on static content.  This centralizes the navigation logic and allows changes to be rapidly deployed globally across the application – all the better to save time with.

In our example, to use templated pages for various operations, the DDT processes the requests with the URL pattern:  “{tablename} / {action}” . It maps a Tablename to the requested table in the data model while the action is mappd to a particular template in the Page Templates folder, which contains pages for each possible action. This way, it responds with a fully templated page based on the requested action.

Use of Meta data and Field Templates

DDTs read the Metadata of the data model at run time and identify the type of each field being used. Then, according to the look-up rules, the determine the most appropriate control to be loaded. These rules give priority to the control types described in the UIHint attribute, and without this the template will load a control based on the datatype. These controls are available under the TemplateFields folder, and a control is available for every field type, with a view mode as well an edit mode . In short, you want for nothing.

Extending Functionality

Adding Business Logic

Incorporating business logic into a Dynamic Data Website is the next stage, and there are a few easy techniques to do just that.

The data context we added earlier contains the Extensibility Method Definition for each class representation of the data model. These are methods that execute when controls change their statuses, and so are an ideal place to include the business logic. These classes, as well as the Extensibility Method definitions, are defined as partial; leaving room for customization by intrepid developers.

As an example, I’ll validate the Reorder Point against the SafetyStock Level in the Product class. To do that, I create a Product partial class and define some extensibility methods as follows.:


And voila, a validation exception is thrown when the ReorderPoint exceeds the SaftyStockLevel. As you can see, it’s a simple matter to keep the business logic separate from the data and presentation layers.

Changing the way fields render


It is essential that fields in the Dynamic Data Templates can be customized and rendered based on various industry needs. These alterations can range from just changing the format of a date to displaying a third party control in place of a default.

To show you just a few things that are possible, I’m going to implement these changes for the ProductReviews edit view:

  • Change the ReviewDate field to the ‘dd MM yyyy’ date format.
  • Validate the EmailAddress field using RegEx.
  • Validate the Rating field with a character length restriction of 1.
  • UnScaffold the ModifiedDate field.
  • Use a 3rd party control (FreeTextBox) for the Comments field.

One way of doing this is to edit the definition of the ProductReview class in AdventureWKS.designer.cs, but this will cause changes in the data model. In order to keep the data model unchanged, and to extend the ProductReview class’s functionality, the more appropriate approach is  to create a partial class specifying the customization, apply the MetadataType attribute to this class and specify its type as ProductReviewMetadata.

MetadataType sits in the System.ComponentModel.DataAnnotations namespace, which has a variety of attributes that can be used to customize field rendering.  Within the ProductReviewMetadata class the initialized properties are populated with the appropriate attributes as shown here:

Just to give you a running commentary, what I’m doing here is:

  • Setting the DisplayFormat attribute in the ReviewDate property to display dates as ‘dd MM yyyy’.
  • Using the RegularExpression attribute to specify the validation expression for the EmailAddress property.
  • Using the Range attribute to specify the range on the Rating property.
  • Setting the UIHint attribute on Comments property to the name of the user control. I’m using the FreeTextBox 3rd party control as this non-default option.
  • Setting the Scaffold attribute to false on ModifiedDate to disable the scaffolding.

And these gloriously simple tweaks produce this:



As you can see, the ReviewDate field format has now changed and the ModifiedDate fields are hidden in the list view, and the 3rd party control and validation functions are all visible. Easy as that.

Dynamic Data Controls

Dynamic Data Templates provide very efficient mechanisms for binding data to templated, data-bound controls using DynamicControl, DynamicField Control and DynamicDataManager controls in the System.Web.DynamicData namespace.

DynamicDataManager is a control that must be included in a page to gain Dynamic Data Support. Both the DynamicControl and DynamicField controls render the appropriate control at run time, based on the field type and provide data validations based on the data model. And these controls can mostly be smoothly and easily brought into play when building custom pages.

DynamicField Control

The DynamicField control allows you to bind a data field (or data fields) when populating templated bind controls. The DataField property lets you specify the fields to be bound, and to show what I mean, I’ll create a custom look for the Adventure Works vendors page; the AutoGeneratedColums is set to false in the GridView control, and the fields to display are specified using DynamicField, as seen here:

And here is what that will look like when we run the application:


Use of DynamicControl

In contrast to the DynamicField control, the DynamicControl lets you specify the display mode being used. For example, to provide inline editing in a templated data-bound control, such as a GridView, we specify one control in ItemTemplate and another in EditItemTemplate. Let’s use a DynamicControl instead. We’ll specify the field to bind in the DataField propety, and mode of display in the Mode property. The Mode property varies as ReadOnly, Edit and Insert.

It’s worth bearing in mind that both controls share some common features, such as DataFormatString (for specifying date formats), NullDisplayText (sets the default text for when field values are null) and ApplyFormatInEditMode (a bool value to indicate whether to apply formatting in the edit mode or not).


With a stabilized model and a well structured solution, the Dynamic Data Templates provide a quick and easy way of building up fully functional data-driven applications in minutes. Even better, you can extending DDTs to suit industry needs with minimal hassle. Unlike other RAD tools, Dynamic Data is much cleaner both in terms of the code and structure. It is simply an elegant way of building up a fully functional data driven application in minutes, and with its templates and routing systems, it provides more functionality with less code.