An Introduction to Dynamic Data
Rapidly Create Rich Data-bound Web Sites
October 30, 2009
From the Source
ASP.NETVERSIONS: 3.5
An Introduction to Dynamic Data
Rapidly Create Rich Data-bound Web Sites
By Marcin Dobosz and Scott Hunter
Creating even a simple data-driven Web site from a defaultASP.NET project can be a time-consuming task. One of the new features of the.NET 3.5 SP1 release that aims to address this is a framework called DynamicData for rapidly creating rich data-bound Web sites.
Getting started with Dynamic Data is as simple as:
Creating a new project using the Dynamic Data projecttemplate.
Generating a data model from a database (bothLINQ to SQL and Entity Framework ORM solutions are supported).
Registering the model with the Dynamic Dataruntime.
The result is a fully functional Web site without-of-the-box support for CRUD operations, foreign-key relationshipnavigation, automatic validation, and filtering. You can take the defaultappearance and functionality and selectively replace or modify the site atvarious levels of granularity, such as changing the look of the entire site or simplymodifying how fields from a single column in a single table are displayed. TheDynamic Data framework enables this by using scaffolding, templates, metadata,and convention-based naming. It also includes enhancements to data source controls,as well as to the DetailsView, FormView, GridView, and ListView controls. Thisarticle provides an introduction to the new features in Dynamic Data.
Scaffolding and Page Templates
A key feature of Dynamic Data is automatic scaffolding ofthe tables in a data model. Dynamic Data scaffolds a table page by firstautomatically discovering information about the data from the model. Using thisinformation, it then dynamically modifies a page template, sets up theappropriate columns and filters for data-bound controls, and populates thosecontrols with data from the database. This means that a single page templatecan be used to generate UI for any number of tables, regardless of what typesof data or relationships they contain.
To enable scaffolding, you must register the data modelwith the Dynamic Data runtime in the site s Global.asax file. The followingexample shows code that you might use to register a LINQ to SQL data contextclass for the Northwind database:
MetaModel model = new MetaModel();
model.MetaModel.RegisterContext(typeof(NorthwindDataContext),
new ContextConfiguration() { ScaffoldAllTables = true });
Figure 1 shows the result of running the application. ADynamic Data project has a starter Web page that displays a list of tables inthe data model. When you click a table in the list, you browse to a scaffoldedpage for that table.
Figure 1: Starter page of a DynamicData project.
Figure 2 shows a scaffolded master/details page for theProducts table. The default Dynamic Data master/details page template does thefollowing:
Adds filtering drop-down controls for Booleancolumns (for the Discontinued field) and foreign-key columns (for the Categoryand Supplier fields).
Displays foreign-key columns (Category andSupplier) using meaningful textual representations (rather than displaying anumeric id value) that are rendered as hyperlinks. Clicking a link navigates toa scaffolded page for the parent table. In edit mode, foreign keys are renderedas drop-down lists that let a user modify the foreign-key value for thatrecord.
Turns one-to-many relationship columns(Order_Details) into hyperlinks that navigate to a scaffolded page for thattable.
Provides a customized GridView pager control.
Provides a DetailsView control for displayingthe details of a selected record.
Figure 2: A sample scaffold page.
Page templates are ordinary ASP.NET pages, and editing apage template allows you to globally change the behavior and appearance of allscaffolded pages in the site. In addition to the default master/details pagetemplate, Dynamic Data ships with individual list, details, edit, and insertpage templates for performing CRUD operations on separate pages. Changingtemplates or adding new ones requires only a minor configuration change.Additionally, you can implement custom pages for any table to override thescaffolding behavior for that table. The Dynamic Data runtime willautomatically discover the existence of a custom page and use it as the pagetemplate for the table.
Field Templates
Standard ASP.NET data-bound controls such as GridView orDetailsView can automatically generate columns based on the kind of data towhich they are bound. However, customizing even a single column (for example,changing display style or adding validators) requires that you create bound ortemplated columns for each data field. Dynamic Data improves this experience byintroducing dynamic field templates.
Field templates are reusable user controls that render asingle data-bound field. A Dynamic Data-enabled GridView control will choosethe appropriate field template based on the field s type. For example, theGridView will use a textbox for string fields and a checkbox for Boolean fields(see Figure 3 for a list of default field templates). You also can specify whichfield template is used for a field by declaring an override, as you ll see inthe metadata section later.
Field Template | Data Type | Rendered with |
---|---|---|
Boolean | Boolean | A CheckBox control. |
Children | A HyperLink control that navigates to a page that lists the records associated with the row. | |
DateTime | DateTime | A TextBox control with optional RequiredFieldValidator and DynamicValidator controls in edit mode. |
Decimal | Double, Float, Decimal | A TextBox control with optional RequiredFieldValidator, CompareValidator, RangeValidator, and RegularExpressionValidator controls in edit mode. |
ForeignKey | A HyperLink control that links to the associated entity in display mode, or a DropDownList control in edit mode. | |
Integer | Int32, Int64, Int16 | A TextBox control with optional RequiredFieldValidator, CompareValidator, RangeValidator, and RegularExpressionValidator controls in edit mode. |
Text | String | A TextBox control with optional RequiredFieldValidator, RegularExpressionValidator, and DynamicValidator controls in edit mode. |
TextArea | String | A TextBox control that is set to multi-line mode, with optional RequiredFieldValidator, RegularExpressionValidator, and DynamicValidator controls in edit mode. |
Figure 3: DefaultDynamic Data project field templates.
When you don t want the control to automatically generatecolumns, you can declare the set of columns to be displayed by using a new typeof data control field called DynamicField. A DynamicField control automaticallychooses the correct field template to use. A complement of DynamicField is theDynamicControl control, which can be used in any custom content template, suchas inside a TemplateField or inside the FormView or ListView controls.
Together, DynamicControl and DynamicField controls reducea lot of code duplication that is characteristic of data-bound controltemplates. For example, to customize how date fields are displayed in editmode, you simply need to modify the DateTime edit template once in anapplication and the change will be reflected across all Dynamic Data pages.
Metadata
A database schema contains a lot of information that canhelp automatically build a more functional user interface. Dynamic Dataautomatically extracts model metadata and uses it to drive the behavior of thepage templates and the field templates.
For example, Dynamic Data uses the following to enhancethe UI:
Information about associations between tables todisplay foreign-key columns and use them for navigation between tables.
Nullable column information to determine whethera field is required.
Data-type information to add validation for afield value.
String-length information to restrict themaximum length of text inputs.
Dynamic Data supports additional metadata attributes youcan declare on the data model to provide information that cannot beautomatically detected from the database schema. Figure 4 lists supportedmetadata attributes. Attributes such as RegularExpression are used by fieldtemplates to enable validation controls. You also can create and use custommetadata.
Attribute | Description |
---|---|
DataType | Provides a way to declare specific semantic information about a column, independent of storage type. For example, a ZIP code might be stored as either an integer or a string. |
Description | Specifies a longer description for a column. The description is presented as a tooltip when a user holds the mouse pointer over the field when editing. |
DisplayColumn | Specifies which column to use as the textual representation of a row. The values of that column are used as the labels in elements of a foreign-key drop-down list. |
DisplayFormat | Allows you to specify formatting and string-conversion options. |
DisplayName | Specifies a friendly display name for a column used in the header text. |
MetadataType | Specifies the associated metadata type for an entity type of the data model. |
Range | Specifies a minimum and maximum range for values of a column. |
RegularExpression | Specifies a regular expression to use as a validation pattern in edit mode. |
Required | Specifies that a field must have a value in edit mode. |
Scaffold | Specifies whether a table or column should be included in a scaffold page. |
StringLength | Specifies the maximum length of a string field. |
UIHint | Specifies which template control to use for the UI of a column. |
Figure 4: Metadataattributes used by the Dynamic Data runtime.
You can annotate the data model using CLR metadataattributes. Both LINQ to SQL and the Entity Framework generate data modelsusing partial classes, which means a class definition can be split acrossmultiple files. This allows you to write the metadata code in a separate filefrom the generated model, which ensures that your custom code is notoverwritten if the model is regenerated.
Adding metadata to a model object begins with creating apartial class whose name matches the data-model class to which you want to addmetadata. In this partial class, you mark the class by using an attribute thatbinds a metadata type with the model object class. The skeleton of a partialclass with a metadata attribute might look like this:
[MetadataType(typeof(ProductMetadata))]
public partial class Product {
}
The MetadataType attribute specifies the type(ProductMetadata in this example) that contains metadata for the object (theProduct class). The associated metadata type is a class that serves as a proxyfor the metadata attributes. Attributes declared on properties of theassociated metadata type that match properties of the main type will be treatedby the Dynamic Data runtime as if they were declared on the main type itself.Therefore, you can create a metadata class, declare skeleton properties in themetadata class, and mark these properties with attributes. This has the sameeffect as if you marked the properties of the original data-model class withthose attributes.
You cannot declare the metadata attributes directly inyour partial class (here, the Product class) because the C# and Visual Basiccompilers cannot directly apply metadata attributes to class members if theattributes are defined in a partial class in another file. The metadata proxyclass solves this limitation.
To be recognized by the Dynamic Data runtime, theassociated metadata type properties must have public visibility and names thatmatch the names in the main type.
The following example of the ProductMetadata classillustrates these metadata attributes for the Products table:
The ProductName field is marked with adescription attribute that displays a tooltip when users are editing the field.
The QuantityPerUnit field is marked as arequired field.
The UnitsInStock field is marked as having arange between 0 and 100. If the entered value falls outside the specifiedrange, the specified error message is displayed:
public class ProductMetadata {
[Description("Enterthe name of the product")]
public object ProductName{ get; set; }
[Required]
public objectQuantityPerUnit { get; set;}
[Range(0, 100,ErrorMessage = "Enter a valid value.")]
public objectUnitsInStock { get; set; }
}
Model Validation
Metadata attributes such as Range, Required, and RegularExpressionprovide a way to express simple validation rules. More complex rules can beadded to the data model using the extensibility methods that LINQ to SQL andEntity Framework expose.
Each field in the data model has a correspondingOnChanging partial method that is called when the field value changes. TheDynamic Data runtime intercepts any validation exceptions that are thrown fromthese methods, and displays the exception message text next to the associatedfield. The following example illustrates how to add validation to theProductName property of the Product class:
public partial class Product {
partial voidOnProductNameChanging(string newValue) {
if (newValue != null&& !newvalue.StartsWith("ACME")) {
throw newValidationException("Product names must
start withACME.");
}
}
}
Figure 5 shows an example of what the Web page will looklike when the validation error is raised.
Figure 5: Dynamic Data page showingmodel validation in action.
Dynamic Data Folders and Files
A Dynamic Data project in Visual Studio is similar to aregular ASP.NET project, but includes additional folders and files. Inaddition, some files that are typical in ASP.NET Web projects have special usesin Dynamic Data.
Figure 6 lists the additional elements in a Dynamic DataWeb project, and provides a short description of how each element is used.
Location | Contains |
---|---|
DynamicDataContent | Miscellaneous content, including images, the user control used to display filters, and a pager control. |
DynamicDataCustomPages | Optional custom pages that override the scaffolded pages on a per-table basis. |
DynamicDataFieldTemplates | User controls that render individual columns. These include display and edit templates for numbers, Boolean values, text, dates, and relationships. |
DynamicDataPageTemplates | Page templates used for scaffolding. A Dynamic Data project contains a ListDetails template (the default), as well as List, Details, Edit, and Insert templates. |
Default.aspx | The site s starting page, with links to all scaffolded tables. |
Global.asax | Code to register a data context object with Dynamic Data. |
Site.master | The master page that is common to all page templates. |
Figure 6: Layoutof a default Dynamic Data project.
Just Getting Started
This article provides an introduction to Dynamic Data.There are many other aspects and advanced scenarios in this feature, such as:
URL routing. This lets you specify how URLs mapto tables and which UI is shown.
Field templates. These let you write fieldtemplates to customize column display and editing.
Regular pages. You can use Dynamic Data in anyASP.NET page by placing a DynamicDataManager control on the page andregistering data controls with it.
Custom pages. You can customize the global pagetemplates on a table-by-table basis by using normal ASP.NET programmingtechniques.
These topics will be covered in future articles.
Marcin Dobosz is adeveloper on the ASP.NET team. He currently isworking on the Dynamic Data feature. You can find him online at http://blogs.msdn.com/MarcinOn/.
Scott Hunter is aprogram manager on the ASP.NET team. He currentlyis working on the Dynamic Data feature. Scott has been working in the industry formore than 20 years and has spent the past seven years building Web applicationson the ASP.NET platform. You can find himonline at http://blogs.msdn.com/scothu/.
Read more about:
MicrosoftAbout the Author
You May Also Like