ASP.NET DynamicData: An Introductory Demo

I had a bit more time on my travels, so I cooked up this brief introduction to Dynamic Data.  I tried a different approach this time by showing what Dynamic Data adds to our existing data story. 

More information on Dynamic Data:  https://asp.net/dynamicdata

To do this demo, install Visual Studio 2008 SP1 and the Dynamic Data update.

I started off with a new, blank Dynamic Data Web Site

image

But rather than going directly into Dynamic Data features, I thought I'd review were we are today with .NET Framework 3.5 briefly. 

Add New Item and select "Linq to Sql Classes" (notice this works nearly the same with Entity Framework

image

Then add a couple of tables from Northwind.  I am using Products, Categories and Suppliers. 

image

 

Now add a new Web Form, creatively called Default2.aspx

In design View, add a GridView control and set up its datasource via the smart tag.

Use the LinqDataSource and change the table to Products

image

under Advanced, but sure to enabled Update.

image

Run it...

Overall this looks good. 

 

But there are a couple of areas it could get better.  For example, those IDs, they are meaningless to my users... I need to go in write code the handle them. 

image  

And Validation, right now i just get an exception if invalid data is entered.

image

Ok, we have set the stage... Let's see what help Dynamic Data can give us. 

First we need to enable Dynamic Data.  Like all good features, it is off by default!

In Global.asax, un comment out the model.RegisterContext method and set it to the NorthwindDataContext class.

 model.RegisterContext(typeof(NorthwindDataContext), 
    new ContextConfiguration() { ScaffoldAllTables = true });

In Default2.aspx, add the DynamicDataManager

image

Finally, in Default2.aspx.cs, in Page_Load() let's ask our DynamicDataManager to mange our GridView.

 DynamicDataManager1.RegisterControl(GridView1);

 

Now, just a couple of tweaks to our Gridview, delete the columns collection, enable AutoGenerateColumns and AutoGenerateEditButton.  

     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" 
        DataKeyNames="ProductID" DataSourceID="LinqDataSource1" AutoGenerateEditButton="True">
    </asp:GridView>

Run it...

Notice that Category and Suppliers have real names rather than IDs and when you edit them, you get a drop down for options.  Dynamic Data knows more about your data model and can therefore provide much better defaults.  

image

image

Data validation is a lot cleaner as well, notice how Dynamic Data pulls data validation from the model and does the right thing on the client? 

image

 

From here you can take advantage of all the other great Dynamic Data features to customize the UI.  More on that later.

Download the full sample