Skip navigation

Dynamic Data Primer

Integrate ASP.NET Dynamic Data into Existing ASP.NET Projects

INETA Community Voices

LANGUAGES: ALL

ASP.NET VERSIONS: 3.5

 

Dynamic Data Primer

Integrate ASP.NET Dynamic Data into Existing ASP.NET Projects

 

By Rachel Appel

 

Microsoft s ASP.NET Dynamic Data is a new Web technology that enables Web developers to quickly create Web applications that consume data and offer basic CRUD operations, while providing a mechanism for easy maintenance based on a set of generated templates.

 

The basis of an ASP.NET Dynamic Data Web site or Web application is to use either a LINQ to SQL or an Entity Framework data model that interacts with both the database and the ASP.NET pages via the DynamicDataManager control. The DynamicDataManager control traffics the data between the data model and Web forms controls, such as a GridView, ListView, or DetailsView.

 

The RTW version of ASP.NET Dynamic Data is available in the Visual Studio 2008 Service Pack 1 and can be downloaded from http://www.asp.net/dynamicdata.

 

Enabling Web Apps for Use with Dynamic Data

A few changes to the configuration of existing Web sites and Web applications are needed before we can start integrating ASP.NET Dynamic Data s features into them. If you are using Visual Studio Web Application Projects, you ll need to add to your project a reference to these libraries:

  • System.Web.DynamicData
  • System.Web.Abstractions
  • System.ComponentModel.DataAnnotations
  • System.Web.DynamicData
  • System.Web.Routing

 

If you are using Visual Studio Web sites, there is no need to set references.

 

Next, you ll want to modify the web.config file so the runtime is aware of the new ASP.NET Dynamic Data libraries. Add to the web.config file under the <compilation> section the lines shown in Figure 1.

 

<add assembly="System.Web.Extensions, Version=3.5.0.0,

 Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add assembly="System.Web.Abstractions, Version=3.5.0.0,

 Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add assembly="System.Web.Routing, Version=3.5.0.0,

 Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

<add assembly="System.ComponentModel.DataAnnotations,

 Version=3.5.0.0, Culture=neutral,

 PublicKeyToken=31BF3856AD364E35"/>

Figure 1: Dynamic Data libraries in the web.config file.

 

Also in the web.config file, you can add to the <pages>/<controls> section the sample code provided in Figure 2.

 

<add tagPrefix="asp" namespace="System.Web.DynamicData"

 assembly="System.Web.DynamicData, Version=3.5.0.0,

 Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

Figure 2: Dynamic Data control in the web.config file.

 

This will enable the DynamicData control, which allows us to extend the dynamic features for use with the standard ASP.NET controls.

 

Finally, the last web.config modification entails adding Web server support. If you are using IIS5, IIS6, or the ASP.NET development server (Casini), you ll add to the <httpModules> section the line shown in Figure 3A. If you re using IIS7, you ll add to the <system.webServer>/<handlers> section the code shown in Figure 3B.

 

<add name= UrlRoutingModule

 type="System.Web.Routing.UrlRoutingModule,

 System.Web.Routing, Version=3.5.0.0, Culture=neutral,

 PublicKeyToken=31BF3856AD364E35" />

Figure 3A: Configure the Web server in the web.config file.

 

<add name="UrlRoutingModule"

 type="System.Web.Routing.UrlRoutingModule,

 System.Web.Routing, Version=3.5.0.0, Culture=neutral,

 PublicKeyToken=31BF3856AD364E35"/>

<add name="UrlRoutingHandler" preCondition="integratedMode"

 verb="*" path="UrlRouting.axd"

 type="System.Web.HttpForbiddenHandler,

 System.Web, Version=2.0.0.0, Culture=neutral,

PublicKeyToken=b03f5f7f11d50a3a"/>

Figure 3B: Configure the Web server in the web.config file.

 

After making changes to the web.config file, we need to set up the dynamic URL routing system. URL routing is the process of mapping URLs in the address bar to a physical location or file, and allows for clean URLs and URLs without extensions. Adding Dynamic Data routing to the application makes it possible to use a data model from LINQ to SQL or Entity Framework as the basis for URL mapping. Routing is coded in the Application_Start event of the global.asax file rather than configured; a sample route is displayed in Figure 4.

 

routes.Add(new DynamicDataRoute("{table}/{action}.aspx") {

   Constraints = new RouteValueDictionary(

        new { action = "List|Details|Edit|Insert" }),

   Model = model

});

Figure 4: Define routing in the Application_Start event.

 

The URL routing system specifically for ASP.NET Dynamic Data maps to a folder named PageTemplates. This folder resides under the DynamicData folder that is located in the root of the current Web application. The DynamicData\PageTemplates folder will need to be added at this time. There are a few other predefined folders that can be added to the DynamicData folder, as well, but only one more is needed for enabling Dynamic Data: the FieldTemplates folder. You ll create this folder under the DynamicData folder.

 

Next, add to your application a data model (either LINQ to SQL or Entity Framework), then register that model. You can register the model in the global.asax file by adding to the Application_Start event the code provided in Figure 5.

 

model.RegisterContext(typeof(NorthwindEntities),

new ContextConfiguration() { ScaffoldAllTables = true });

Figure 5: Registering the data model.

 

Registering the data model provides access to the data model by the Dynamic Data controls so create, retrieve, update, and delete (CRUD) operations can be performed on the data.

 

At this point the Web application is completely enabled for use with ASP.NET Dynamic Data and it s now possible to start leveraging its new capabilities.

 

Customizing Current Pages

When dynamic behavior is enabled, the controls on the page will be connected to the data model via the DynamicDataManager control. Unlike the standard behavior in Web forms controls there is now no need to write typical CRUD, validation, UI logic, and other standard glue code in the code-behind file it is all dynamically handled for you. ASP.NET Dynamic Data allows the developer to declaratively configure a set of controls that will display and handle all operations that previously required the manual creation of templates, data access, and UI logic code.

 

To enable the dynamic behavior provided by Dynamic Data to other controls on the page, you must add a DynamicDataManager to the page, then register it. Out of the box, controls such as the GridView, ListView, DetailsView, and FormView support dynamic behavior when a DynamicDataManager control is present on the Web form.

 

Figure 6 contains an example of declaratively configuring the DynamicDataManager, as well as registering it in the code-behind file.

 

In the .aspx file:

<asp:DynamicDataManager ID="DynamicDataManager1"

 runat="server" AutoLoadForeignKeys="true" />

 

In the code-behind file:

protected void Page_Init(object sender, EventArgs e) {

   DynamicDataManager1.RegisterControl(GridView1, true);

}

Figure 6: The DynamicDataManger control.

 

You can write custom validation and UI logic code by using extension methods of the data model s entities rather than adding code to the code-behind file. The code will then be located in one central area for all dynamically enabled pages, enforcing the don t repeat yourself (DRY) development technique, as well as a clean separation of concerns.

 

The application has everything but dynamic field templates defined. Dynamic pages can be browsed, but because there are no dynamic field definitions, only blank entries will be displayed. (Note: If you set the AutoGenerateColumns= false and define fields as bound columns or item templates, they ll display; however, this violates the DRY principle, as well as the point of using dynamic field generation in the first place.)

 

Creating Dynamic Field Templates

Dynamic field templates define and control the display and formatting using user controls and additionally supplying extra information with data annotations in the data model through attributes. Dynamic Data renders dynamic fields by matching the name of the control with the data type in the data model for the particular mode (read only, edit, or insert) requested at run time. For example, a user control named integer.ascx will display integer data in read only mode, while integer_edit.ascx will display integer data in edit or insert mode. If Dynamic Data doesn t find a field template defined for a particular data type it will try to default to an appropriate type to display. If it finds nothing to fall back on, it will display a blank area where that field should render.

 

You have two options for adding user control templates to a project:

  • Create a new ASP.NET Dynamic Data Web site and copy the .ascx files from \DynamicData\FieldTemplates to the same directory in your application.
  • Manually create the .ascx files and add the controls.

 

The easiest way to include the field templates is to create a new Dynamic Data Web site and copy the base templates over, then you can modify them as needed. For data types such as images or variant data, you ll need to create your own user controls to handle that data. If you manually create a user control, you must ensure that it inherits from the System.Web.DynamicData.FieldTemplateUserControl class.

 

When you create user controls you can use binding expressions just as you would with regular ASP.NET server controls. The binding expressions available for Dynamic Data are available as members of the FieldTemplateUserControl class, and also can be used in code. Properties of the FieldTemplateUserControl that can be used declaratively are shown in Figure 7.

 

Property

Description

FieldValue

Gets or sets the value of a column in a current row.

FieldValueEditString

Gets the string representation of the value of a column in the current row when the row is in edit mode.

FieldValueString

Gets the formatted string representation of the value of a column in the current row.

Figure 7: Declarative FieldTemplateUserControl properties.

 

To use the declarative FieldTemplateUserControl properties, add markup and the binding expressions to your user control content page, as shown in Figure 8.

 

<asp:Literal runat="server" ID="Literal1"

 Text="<%# FieldValueString %>" />

<asp:TextBox ID="TextBox1" runat="server"

 Text='<%# FieldValueEditString %>' CssClass="droplist">

</asp:TextBox>

Figure 8: User control markup.

 

After creating user controls you ll not physically add them to your pages as you would normally through drag and drop they ll be loaded at run time dynamically as children controls of the appropriate grid controls by the run time.

 

Once you ve created enough field templates for each data type you want to display, your ASP.NET Dynamic Data Web site or Web application should be fully functional and you can browse pages. There are many more customizations that can be done to extend Dynamic Data sites, such as adding dynamically driven hyperlinks, customizing field templates with AJAX controls, and providing extra validation at the metadata model.

 

Conclusion

Integrating ASP.NET Dynamic Data into current Web applications can give you a more flexible approach to maintenance going forward. The ability to extend pages, field templates, and behaviors in one location allows developers to improve existing applications with few code modifications. ASP.NET Dynamic Data provides a mechanism to enforce the DRY principle and assist in separating concerns, making it easy to split functional code groups into UI, business, logic, and other layers.

 

Rachel Appel lives in Northeastern Pennsylvania and is the senior technology consultant at Appel Consulting. Rachel is an ASP.NET MVP and a member of ASPInsiders, and holds the MCT, MCAD, and MCSD certifications. She has been working as an instructor, software developer, architect, and DBA for a variety of organizations. She is the Vice President and a regular speaker of the .NetValley user group, as well as an active member in other user groups of Pennsylvania. Rachel s expertise lies within developing solutions that align business and technology using the Microsoft .NET family of products.

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish