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

Contents

Introduction

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

601-image002.jpg

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:

601-image004.jpg

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.

601-image010.jpg

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.

601-image012.jpg

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.:

601-image018.jpg

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

601-image019.gif

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:

601-image025.jpg

601-image027.jpg

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:

601-image031.jpg

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).

Conclusion

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.

Tags: , ,

  • 68734 views

  • Rate
    [Total: 135    Average: 3.7/5]
  • ryan martin

    this is a great article which covers many features in dynamic data
    Could you upload the demo project that accompanies this article for your readers to download.

  • NVP
  • Anonymous

    Awesome
    Awesome

    <a href=”http://www.nisheethpandya.blogspot.com”>http://www.nisheethpandya.blogspot.com</a&gt;

  • Chris Massey

    Code update
    The code in this article has been changed from screen-grabs to characters – hope you guys find it useful.

  • ramil joaquin

    Video Tutorial about Dynamic Data
    guys you can follow this link to watch the video tutorial about dynamic data http://developercontainer.blogspot.com/search/label/Dynamic%20Data

  • Anonymous

    >
    ;gt;

  • Anonymous

    Web Services
    Is it possible to use web services with this method?

  • Jack the DBA

    Stored Procedures
    How would you use stored procedures with Dynamic Data?

  • Gayani

    Re: Web Services
    Re: Is it possible to use web services with this method?

    Yes you can use a webservice. But it depends on the purpose of it and where you want to use it.

    Thx,
    Gayani

  • Gayani

    Re: Stored Procedures
    Re : How would you use stored procedures with Dynamic Data?

    The Dynamic Data uses methods with in System.Web.DynamicData which contains almost all the methods defined to support the database activities. The built-in page templates in DDT uses these methods.
    But apart from using the in built page templates, you can define your own custom pages and create your own data access classes, over there you can use the stored proceedures with the same DataContext.

    Thx,
    Gayani

  • Peter Gfader

    More security stuff would be interesting..
    Like how to restrict some users/roles from viewing/editing a table.

  • Gayani

    Re: More security stuff would be interesting..
    Re: Like how to restrict some users/roles from viewing/editing a table.

    It is posible to implement the ASP.NET Role based security model in to the web application using the WAST (Web Site Administration Tool). To apply the access rules on to a particular table, it’s better to develop it as a custom page and give access rights to the particular folder (ex: Custom Pagers-> Vendor), for the required user/role.

    Thx,
    Gayani

  • Daniel Penrod

    MVC?
    Is this Microsoft’s way of implementing a type of the Model View Controller (MVC) Framework? It seems to me like the same idea. Am I wrong to think that?

  • Anonymous

    its a boring article
    its a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring articleits a boring article

  • MAJID

    MAJID
    MY NAME IS MAJID ALI I LOVE YOU MY NAME IS MAJID ALI I LOVE YOU MY NAME IS MAJID ALI I LOVE YOU

  • Gayani

    Re: MVC?
    Re: Is this Microsoft’s way of implementing a type of the Model View Controller (MVC) Framework? It seems to me like the same idea. Am I wrong to think that?

    Well, the Dynamic Data Templates, use a similar technique used in MVC Frameworks URL Routing system, so you can consider this as one such instance where a similar routing technique is used.

    Thank you,
    Gayani

  • Landing Page Templates

    gfgfgfgf
    The Dynamic Data uses methods with in System.Web.DynamicData which contains almost all the methods defined to support the database activities.

  • piyush_varma

    Ho to selectively display one or more tables in the default.aspx page?
    What do I need to modify to list only one table in a web page? I need to direct individual users to the selected table only.

    Or how do I call to display individual table?

    Thank you,

    Piyush Varma

  • piyush_varma

    Ho to selectively display one or more tables in the default.aspx page?
    What do I need to modify to list only one table in a web page? I need to direct individual users to the selected table only.

    Or how do I call to display individual table?

    Thank you,

    Piyush Varma

  • klca

    Adding Page Templates
    Dear Gayani Devapriya,

    My name is Carlos Porras. I am from El Salvador.

    Currently I am fcing the following problem:

    I have been trying to customize an inventory system that I had alredy elaborated like 20 years ago in FoxPro. It works fine, doesn’t really need any major change in its logic or business rules but unfortunately FoxPro is not web based so I am working in migrating it to ASP.Net/C#.

    I decided to try using Dynamic Data but I have a problem in how to redirect URL properly as to use a single customized template page for all of my 52 “reference tables” such as: type of customer, type of account, type of product, type of address, and so on.

    I know that if I create 52 different folders inside the Dynamic DataCustom Folders I will get the job done but it seems quite embarrassing for me doing that if I know for sure that there must be a way of doing this by means uf using a single template instead of 52.

    I also need to eliminate the “FilterRepeater” (currently I have just added the visible equals to false) because I will need to display a GridView by using a Session parameter (company_code) that I will be gathering from login time. In doing this I don’t need the user to select any other company but his.

    The only problem is that by setting that parameter to “false” you don’t really avoid the program in building behind the scenes all of the foreign keys that are not going to be displayed anyway. That’s a waste of time and obviously of the server resources.

    It’s a shame that there is not enough “digestible” information about the Dynamic Data framework and is really hard trying to accomplish this without proper support from MS. (that’s what I think: all of this should be easier)

    Can you help me …. desperately …. PLEASE !!!!

  • ypradeep23

    Source Code please…
    Great Article…Source code please…

  • GerardoGala

    Modifying DataContext on the fly
    Hi All!

    Has someone tried to modify the mappingSource of the DataContext at run-time before anything is excecuted. I want to able to change the datasource at run-time to point at different databases depending on who the User is.

    Right now it is using this code:

    base(global::System.Configuration.ConfigurationManager.ConnectionStrings[“FAMP_ConnectionString”].ConnectionString, mappingSource)

    Thanks!

  • ManishGhadge

    Need help about dynamic template
    Hello madam

    I want to develop website in which user can add,edit,delete his control at run time and according to that DB should be gen rate at sql server.So want to know is this dynamic template is helpful to me or if any other way is there to do this things.
    So please help me for this problem.

    Thanks in advance