Enabling Dynamic Data for Existing Projects

Dynamic Data features that shipped in the .NET Framework 3.5 SP1 brought new features such as the following:

· Field templates – These provide data-type-based templates for data-bound controls. Field templates provide a simpler way to customize the look of data controls than using template fields for each field.

· Validation – Dynamic Data lets you use attributes on data classes to specify validation for common scenarios like required fields, range checking, type checking, pattern matching using regular expressions, and custom validation. Validation is enforced by the data controls.

However, these features had the following requirements:

· The data-access layer had to be based on Entity Framework or LINQ to SQL.

· The only data source controls supported for these features were the EntityDataSource or LinqDataSource controls.

· The features required a Web project that had been created using the Dynamic Data or Dynamic Data Entities templates in order to have all the files that were required to support the feature.

A major goal of Dynamic Data support in ASP.NET 4 is to enable the new functionality of Dynamic Data for any ASP.NET application. The following example shows markup for controls that can take advantage of Dynamic Data functionality in an existing page.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True"

DataKeyNames="ProductID" DataSourceID="LinqDataSource1">

</asp:GridView>

<asp:LinqDataSource ID="LinqDataSource1" runat="server"

ContextTypeName="DataClassesDataContext" EnableDelete="True" EnableInsert="True"

EnableUpdate="True" TableName="Products">

</asp:LinqDataSource>

In the code for the page, the following code must be added in order to enable Dynamic Data support for these controls:

GridView1.EnableDynamicData(typeof(Product));

When the GridView control is in edit mode, Dynamic Data automatically validates that the data entered is in the proper format. If it is not, an error message is displayed.

This functionality also provides other benefits, such as being able to specify default values for insert mode. Without Dynamic Data, to implement a default value for a field, you must attach to an event, locate the control (using FindControl), and set its value. In ASP.NET 4, the EnableDynamicData call supports a second parameter that lets you pass default values for any field on the object, as shown in this example:

DetailsView1.EnableDynamicData(typeof(Product), new { ProductName = "DefaultName" });

Posted in: programming asp.net | Tags: asp.net 4.0 linqdatasource dynamic data .net 3.5 entitydatasource