Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Developing ASPDynami Data

Developing ASP dynamic Data Microsoft Labs

Uploaded by

thusith0106
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Developing ASPDynami Data

Developing ASP dynamic Data Microsoft Labs

Uploaded by

thusith0106
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Microsoft Virtual Labs

Developing ASP.NET Dynamic


Data Web Applications
Developing ASP.NET Dynamic Data Web Applications

Table of Contents
Developing ASP.NET Dynamic Data Web Applications .......................................................... 1
Exercise 1 Setup Lab .....................................................................................................................................................2
Exercise 2 Creating a Data-Driven Web Application ....................................................................................................5
Exercise 3 Adding Additional Metadata and Validations to the Model ...................................................................... 16
Exercise 4 Customizing a Dynamic Data Application................................................................................................. 22
Developing ASP.NET Dynamic Data Web Applications

Developing ASP.NET Dynamic Data Web


Applications

Objectives After completing this lab, you will be better able to:
 Create a data-driven web application using ASP.NET Dynamic Data
 Add validation to the data model of your application
 Customize ASP.NET Dynamic Data rendering
 Customize ASP.NET Dynamic Data pages
 Customize ASP.NET Dynamic Data fields

Scenario ASP.NET Dynamic Data provides the Web application scaffolding and
templating that enables you to build rich data-driven Web applications. This
scaffolding is a mechanism that enhances the functionality of the existing
ASP.NET framework by adding the ability to dynamically display pages or fields
based on your underlying data model, without having to create pages manually.
Dynamic Data infers the resource to display and the view to create from the URL
of the request. This mechanism is very flexible. It provides a view of the data
based on default templates, while enabling complete customization. You can
customize the display for a specific resource or for the web application as a
whole.

Estimated Time to 90 Minutes


Complete This Lab

Computers used in this


Lab VistaOffice07

Page 1 of 29
Developing ASP.NET Dynamic Data Web Applications

Exercise 1
Setup Lab

Scenario
You must perform the following steps to prepare your computer for this lab. This consists primarily of creating the
database that will be used in the lab and initializing it with default data.

Tasks Detailed Steps


Complete the following a. Open the folder
tasks on: C:\NETFramework35Enhancements_TrainingKit\Labs\AspNetDynamicData
\Setup
VistaOffice07 b. Run the command file SetupEx.cmd. This command file executes a SQL script to
1. Prepare your set-up the database and creates an alias for the database server. It also launches the
computer for this lab Visual Studio installer file that installs the code snippets for the lab. For
convenience, much of the code is available as Visual Studio code snippets.
c. Press enter or type “yes” when requested in the command prompt until the Visual
Studio Content Installer window appears.
2. Setup the Visual a. When prompted, choose all items in the installer.
studio snippets

Page 2 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

b. A dialog box appears warning that the file is not signed; choose Yes to proceed
anyway.

c. When prompted for the location of the snippets, highlight all snippets, click the
check box next to My Code Snippets, and click Next.

Page 3 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
d. Click Finish to install the code snippets.

e. The installation should proceed and install all snippets.

Page 4 of 29
Developing ASP.NET Dynamic Data Web Applications

Exercise 2
Creating a Data-Driven
Driven Web Application

Scenario
In this exercise you will learn the fundamentals of ASP.NET Dynamic Data applications, their core concepts, how
they work and how to use them. Through the exercise you will build an application from scratch that lets you
navigate through the entities you added to the data model and its relationships, without having to write a single line
of code.

Tasks Detailed Steps


Complete the following a. Open Microso
Microsoft Visual Studio 2008 from Start | All Programs | Microsoft
tasks on: Visual Studio 2008 | Microsoft Visual Studio 2008.
b. On the File menu, point to New, and click Project.
VistaOffice07 c. In the New Project dialog box select Visual C# |Web.. Make sure that .NET
1. Create a Dynamic Framework 3.5 is selected and select the Dynamic Data Entities Web
Data Application Application project type. You may set the name to AspNetDynamicData and the
Project location to
C:\NETFramework35Enhance
NETFramework35Enhancements_TrainingKit\Labs\AspNetDynamicData
AspNetDynamicData
\Ex01
Ex01-CreatingDynamicDataApp\begin which is the provided folder.
d. Click OK to create the application project.

2. Create the Database a. Add a new folder to your project called Model.. To do this, right-click
right the project
Model and click Add > New Folder.. When the folder is added to your project, rename it
to Model
Model.
b. Add the Entity Data Model that will represent the databasese model. To do this,
click the newly created Model folder and then click Add > New Item. On
right-click
the Add New Item dialog, click on ADO.NET Entity Data Model. Model Type

Page 5 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
AdventureWorks.edmx in the Name textbox and click Add.

c. Select the Generate from database option and click the Next button.
d. Add a new database connection. To do this, click the New Connection… button.
e. If Choose Data Source window appears, then choose Microsoft SQL Server and
press Continue.
f. Enter NETSP1LABS for the server name, select the AdventureWorksLT
ventureWorksLT
database, and then click the OK button.
Note: NETSP1LABS is the default alias for the database server installed when the
SetupEx.cmd script was run at the beginning of this lab.

Page 6 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

g. Enter AdventureWorksContext for the name of the connection string for your
Entity Data Model, and click the Next button.

h. Add some tables to your Entity Data Model.. To do this, expand the Tables node
and select the following tables:
 Product (SalesLT)
 ProductCategory (SalesLT)
 ProductModel (SalesLT)

Page 7 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

i. Change the Model Namespace to AspNetDynamicData.Model and click the


Finish button to save your Entity Data Model.
Note: If you open the AdventureWorks.designer.cs file, you will notice that it now has
the AdventureWorksContext
AdventureWorksContext, Product, ProductCategory and ProductModel classes.
The AdventureWorksContext class represents the connection to your model/database,
and the Product
Product, ProductCategory, and ProductModel classes represent database
tables/entities.
constructor of the AdventureWorksContext class reads the
The parameterless construct
connection string from the Web.config file.
If you open the Web.config file, you will notice that the connection string has been
added in the connectionStrings element.
3. Enabling Scaffolding a. Enable automatic scaffolding feature in the Dynamic Data application. To do this,
open the Global.asax file and find the RegisterRoutes method. Locate the
following comment line near the top of the method:
//model.RegisterContext(typeof(YourDataContextType), new
//model.RegisterContext(typeof(YourDataContextType
ContextConfiguration() { ScaffoldAllTables = false });
Note: Automatic scaffolding is not enabled by default for security reasons, because
you are exposing all the tables in the data model for display and edit operations.
b. Uncomment that line, set the contextType parameter to the Entity Data Model
context you just created ((Model.AdventureWorksContext), ), and set the
ScaffoldAllTables property of the ContextConfiguration class to true. When
done, it should look like the followi
following:
model.RegisterContext(typeof(Model.AdventureWorksLTEntitie
s), new ContextConfiguration() { ScaffoldAllTables = true
});
c. Save and close the Global.asax file.
4. Running the a. Press F5 to run the ASP.NET Dynamic Data Web Application.
Dynamic Data Note: If the dialog Debugging Not Enabled appears, select Modify the Web.config file
Application

Page 8 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
to enable debugging and click OK.
b. You will be redirected by default to a Default.aspx page of the ASP.NET
Dynamic Data Web Application; this page displays a list that contains
con the entities
that you added to the data model.
Note: The Default.aspx home page is in the project’s root folder. It is created by the
Dynamic Data Entities Web Application template. If you wish to change it, you can
open it up and edit it however you want.

c. Click the Product table to see all the products that are persisted in the database.
The scaffolding feature will generate the entire grid view and will make the
appropriate query to the database to retrieve all the products.

Page 9 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

Note: When a field is a foreign key (ProductCategory and ProductModel)


ProductModel
Dynamic Data will look up and display the text version of it from the foreign key table
automatically instead of the Id.

Note: Dynamic data infers that the text to display is the one contained in the first
f text
field found in the foreign key table. So if the foreign key table is not designed in this

Page 10 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
way, unexpected results may occur. This can be solved by customizing Dynamic Data,
a topic which will be covered in the next exercise.
d. You will notice that the Product Categories and Product Models values are
links, so click on ““Road Frames” to navigate to the ProductCategory table with
Road Frames
“Road Frames”” as the selected category. You’ll be taken to a page that displays
that specific category.

e. Go back to the previous page, by clicking the Back button of the browser.
f. At the bottom of the product table you will see paging controls.
controls These controls
appear when the number of rows is large and let you navigate through pages and
select the number of rresults per page to be shown.

Page 11 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

g. Filter the results by ProductCategory field, set the value to Brakes.


Brakes The product
table will refresh to show the products that verify the filter.

Note: Automatic filters are created based on foreign key and boolean fields
field in each
table.

Page 12 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
h. Select the second product by clicking on Details link. The details for that specific
product will be shown at the bottom of the page.

i. Edit the product by clicking the Edit link at the bottom of the details view. Notice
that foreign col
columns
umns are rendered as dropdown lists to improve user experience.

Page 13 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

j. Change the values and then click Update, or click Cancel to cancel the edit
operation.
Note: You can also try Delete and New operations.
k. Close the browser to stop debugging.
5. Adding Metadata to a. Add a Product partial class in order to add metadata attributes related to products.
your Model right-click the Model folder and then click Add New Item.
To do this, right Item On the
Add New Item dialog, click Class. In the Name textbox, enter Product.cs as file
name and click Add.

b. Add namespace directives that refer to the System.ComponentModel and


System.ComponentModel.DataAnnotations namespaces.
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
Note: The System.ComponentModel.DataAnnotations namespace provides attribute
classes that are used to define metadata for ASP.NET Dynamic Data controls.
c. Add the partial keyword to the class definition to make it a partial class.
public partial class Product
d. Add a ProductMetadata class in order to add property-level
level validations related to
products. To do this, add the following code within the Product class you have
just created.
public partial class Product
{
private class ProductMetadata
{
}
}
Note: Because
cause C# and VB languajes don’t allow you to have partial properties, there
is no way of adding additional metadata to your model class’ properties through your
partial Product class. This is where the metadata class comes in. The metadata class
allows you to add property stubs to which you can apply metadata to, and then
associate it to the partial class, which will ultimately get associated to the model.

Page 14 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
e. Associate the ProductMetaData class with the Product class by adding a
MetadataType attribute to the Product class. To do this, add the following code
above the Product class definition.
[MetadataType(typeof(ProductMetadata))]
public partial class Product
{
private class ProductMetadata
{
}
}
f. Add a ProductNumber property to the ProductMetaData class.
private class ProductMetadata
{
public object ProductNumber { get; set; }
}
Note: When creating a metadata class for the sole purpose of adding metadata to a
model class, the type of the metadata properties is not important. This is why the
Name property is defined as object type, when in the underlying model class is defined
as a string type.
g. Apply the DisplayName attribute to the ProductNumber property. To do this,
add the following code above the property definition.
[DisplayName("Code")]
private object ProductNumber { get; set; }
Note: This DisplayName attribute specifies that the property will be shown in the web
application with another name, in this case “Code”.
h. Set off scaffolding generation for the following properties: ThumbNailPhoto,
ThumbnailPhotoFileName and ModifiedDate. To do this, add the following
code to the ProductMetadata class.
private class ProductMetadata
{
...
[ScaffoldColumn(false)]
public object ThumbNailPhoto { get; set; }
[ScaffoldColumn(false)]
public object ThumbnailPhotoFileName { get; set; }
[ScaffoldColumn(false)]
public object ModifiedDate { get; set; }
}
Note: The ScaffoldColumn attribute has a Boolean parameter to specify whether to
create scaffolds for the property, in this way properties which have the
ScaffoldColumn attribute set to false are not displayed.

Page 15 of 29
Developing ASP.NET Dynamic Data Web Applications

Exercise 3
Adding Additional Metadata and Validations to the Model
Mode

Scenario
In this exercise you will learn how to customize an ASP.NET Dynamic Data application applying metadata attribute
to the Entities to adapt them to your own rendering and validation needs.

Tasks Detailed Steps


Complete the following a. Open Microsoft Visual Studio 2008 from Start | All Programs | Microsoft
tasks on: Visual Studio 2008 | Microsoft Visual Studio 2008
2008.. Open the solution file
AspNetDynamicData.sln located in the folder AspNetDynamicData\Ex02-
AspNetDynam
VistaOffice07 AddingMetadataAndValidations
AddingMetadataAndValidations\begin.. Alternatively, you may continue with
1. Add New Tables to the solution created after completing Exercise 1.
the Database Model b. Open the exiting Entity Data Model.. Do this by expanding the Models folder in
solution-explorer and double-clicking on the AdventureWorks.edmx file.
solution file
c. Add some new database tables to the model. To do this, right
right-click
click the model
m
designer and select the Update Model from Database… item. On the Add tab,
expand the Tables node and select the following tables:
 Customer (SalesLT)
 SalesOrderHeader (SalesLT)
 SalesOrderDetail (SalesLT)

Page 16 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
2. Review Application a. Press F5 to run the ASP.NET Dynamic Data Web Application.
Actual State Issues Note: If the dialog Debugging Not Enabled appears, select Modify the Web.config file
to enable debugging and click OK.
b. You will be redirected by default to the Default.aspx page of the ASP.NET
Dynamic Data Web Site; this page displays a list with the tables that you added to
the data model.
c. Click SalesOrderHeader table to see its data and then click the Customer filter
combo box, you will notice that its values are wrong since Dynamic Data cannot
correctly infer which Customer table field to display as the foreign key text.

Note: When a data field is a foreign key of another table, Dynamic Data displays this
column as a link to the other table. Dynamic Data uses the first column of type string
strin
as the link text when the relationship between the tables is a one
one-to
to-one relationship.
d. Press Esc to close the combo. Notice that the date fields aren’t formatted (are
displaying redundant time data).

Page 17 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

e. Close the browser to end this task.


3. Customize a. Add a Customer partial class in order to add validations related to customers. To
Rendering Using right-click the Model folder and then click Add New Item.
do this, right Item On the Add
Attributes New Item dialog, click Class. In the Name textbox, enter Customer.cs as file
name and click Add.

b. Add a namespace directive that refers to the


System.ComponentModel.DataAnnotations namespace.
using System.ComponentModel.DataAnnotations;
c. Add the partial keyword to the class definition to make it a partial class.
public p
partial class Customer
Note: In order to customize the table rendering, you must create a partial class for the
table you want to change, and apply the attributes to the class definition.

Page 18 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

d. Add the DisplayColumn attribute to the Customer class to specify the


CompanyName column as the default foreign key text to be displayed in
relationship tables. Also specify that CompanyName should be the column used
to sort the Customer data. To do this, paste the following code above the partial
class definition.
[DisplayColumn("CompanyName", "CompanyName")]
public partial class Customer
{
}
Note: To change the column that is displayed as the value for the foreign key field as
well as the sort order, you must apply the DisplayColumn attribute to the partial
entity class of the relationship table.
Notice that you didn’t need to create a metadata class for the Customer partial class
because any property-level metadata was applied.
e. Add a SalesOrderHeader partial class in order to add validations related to sales
order headers. To do this, right-click the Model folder and then click Add New
Item. On the Add New Item dialog, click Class. In the Name textbox, enter
SalesOrderHeader.cs as file name and click Add.
f. Add a namespace directive that refers to the
System.ComponentModel.DataAnnotations namespace.
using System.ComponentModel.DataAnnotations;
g. Add the partial keyword to the class definition to make it a partial class.
public partial class SalesOrderHeader
h. Add a SalesOrderHeaderMetadata class in order to add validations related to
sales order headers properties. To do this, add the following code within the
SalesOrderHeader class.
public partial class SalesOrderHeader
{
private class SalesOrderHeaderMetadata
{
}
}
i. Add three properties: OrderDate, DueDate, and ShipDate with the
DisplayFormat attribute applied on the SalesOrderHeaderMetadata class to
specify how dates fields are displayed and formatted.
private class SalesOrderHeaderMetadata
{
[DisplayFormat(DataFormatString="{0:yyyy-MM-dd}")]
public object OrderDate { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public object DueDate { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public object ShipDate { get; set; }
}
Note: The DisplayFormatAttribute has other parameters
(ConvertEmptyStringToNull, DataFormatString and NullDisplayText) which are
optional named parameters. In this case the DataFormatString property is defined to
display the OrderDate, DueDate and ShipDate columns in the yyyy-MM-dd format.
j. Associate the SalesOrderHeaderMetadata class with the SalesOrderHeader
partial class by adding a MetadataTypeAttribute to the SalesOrderHeader

Page 19 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
class.
[MetadataType(typeof(SalesOrderHeaderMetadata))]
public partial class SalesOrderHeader
{
private class SalesOrderHeaderMetadata
{
...
}
}
4. Adding Validations a. In Solution Explorer, open the Model folder. Double-click the Product.cs file to
Using Attributes open it up to add validations related to products.
b. Add a Name property to the ProductMetaData class and apply the Required and
StringLength attributes to it. To do this, add the following code in the
ProductMetaData class.
private class ProductMetadata
{
...
[StringLength(30)]
[Required(ErrorMessage = "Product name is required.")]
public object Name { get; set; }
}
Note: The Required attribute specifies that the property value must not be empty and
the StringLength attribute specifies the maximum length allowed for a string. The
ErrorMessage parameters denote what message to display when the property doesn’t
match the constraint.
c. Add a StandardCost property to the ProductMetaData class and apply the
Range attribute to it. To do this, add the following code in the ProductMetaData
class.
private class ProductMetadata
{
...

[Range(0, 10000, ErrorMessage="Standard Cost should be


between {1} and {2}.")]
public object StandardCost { get; set; }

}
Note: This Range attribute specifies a valid numeric interval for a specific field.The
ErrorMessage parameters denote what message to display when the property isn’t
specified.
All these attributes support the ErrorMessage named parameter that enables you to
specify a message that is displayed when validation fails. The ErrorMessage value
can contain indexed placeholders for the other parameters. For example, the
followings are the possible indexed placeholders’ values that you can use for Range
attribute:
0 - Returns the field name.
1 - Returns the minimum value for the Range attribute
2 - Returns the maximum value for the Range attribute
d. Apply a RegularExpression attribute to the ProductNumber property. To do
this, add the following code shown in bold above the property definition.
[RegularExpression("[A-Z]{2}-[A-Z0-9]{4}(-[A-Z0-
9]{1,2})?", ErrorMessage = "Invalid code.")]

Page 20 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
[DisplayName("Code")]
public object ProductNumber { get; set; }
Note: The RegularExpression attribute specifies a regular expression that will be
used to validate a string. In this case, you are specifying the correct format allowed
for the product number.
5. Adding Validations a. Create the event handler that will be called every time the ListPrice field changes.
Using To do this, open the Product.cs partial class file you have created in the previous
DynamicValidator task and add the partial OnListPriceChanging method. The value to be validated
is passed to the method as a parameter.
[MetadataType(typeof(ProductMetadata))]
public partial class Product
{
partial void OnListPriceChanging(decimal value)
{
}

...
}
b. Implement the validation logic. To do this, insert the following code as the
method’s body.
Note: This method checks that the new ListPrice value entered by the user is a positive
number. If the data does not pass validation, the method throws an exception.
partial void OnListPriceChanging(decimal value)
{
if (value < 0)
{
throw new ValidationException("List Price must be
positive");
}
}
Note: The naming convention for the methods used by the object model follows a
specific scheme. The method name starts with On, followed by the field (column)
name, followed by the event verb. For example, if the column name is ListPrice the
method and the event is Changing, name is OnListPriceChanging.
The exception type thrown in our model method was of type ValidationException.
This is a new type added to the System.ComponentModel.DataAnnotations
namespace that is meant to denote an exception as a result to a data validation error.

Page 21 of 29
Developing ASP.NET Dynamic Data Web Applications

Exercise 4
Customizing a Dynamic Data Application

Scenario
In this exercise you will learn how to customize an ASP.NET Dynamic Data application modifying the defaults data
views to adapt them to your own rendering needs.
Tasks Detailed Steps
Complete the following a. Open Microsoft Visual Studio 2008 from Start | All Programs | Microsoft
tasks on: Visual Studio 2008 | Microsoft Visual Studio 2008
2008.. Open the solution file
AspNetDynamicData.sln located in the folder AspNetDynamicData\Ex03-
AspNetDynamicData
VistaOffice07 CustomizingDynamicData
CustomizingDynamicData\begin. Alternatively, you may continue with the
1. Review Application solution created after completing Exercise 3.
Actual State Issues b. Press F5 to run the ASP.NET Dynamic Data Web Application.
Application
c. You will be redirected by default to the Default.aspx page of the ASP.NET
Dynamic Data Web SiteSite.
d. Click SalesOrderHeader table to see its data. You will notice that the boolean
OnlineOrderFlag field is rendered using a checkbox.

e. Go back to the home pag


page, by clicking Back to home page link or using the
browser’s back button.
f. Click the Customer link to display all customers. You will notice that all fields are
displayed in the grid including some that may be not relevant to the user. It would
be useful tto filter the table only to show the important fields.

Page 22 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

g. Close the browser to end this task.


2. Customize Note: The ASP.NET Dynamic Data scaffolding mechanism uses templates to provide
Rendering for a the default views of data. The templates are basic ASP.NET pages, which mean that
Particular Table you can change the templates and affect the scaffolding across the entire Web
application.
When you create an ASP.NET Dynamic Data application, the project template adds a
DynamicData folder to your project. The following page templates are provided by
Dynamic Data in the DynamicData\PageTemplates folder:

- Details.aspx
Details.aspx: Displays the read-only details for a row in a table.
- Edit.aspx
Edit.aspx: Displays an edit view for a row in a table.
- Insert.aspx
Insert.aspx: Displays an insert view for a row in a table.
- List.aspx
List.aspx: Displays a list of rows from the database.
- ListDetails.aspx
ListDetails.aspx: Displays a list of rows from the databasee along with read-only
read
details for a selected row.
a. Create a Customer folder under the DynamicData\CustomPages
CustomPages folder. To do
this, in Solution Explorer, right-click DynamicData\CustomPages
CustomPages folder, point
to Add and select New Folder. Then enter Customer as the he folder’s name.
Note: The folder’s name must match the name of the table’s view that wants to be
customized.
b. Copy List.aspx under the DynamicData\PageTemplates folder to the newly
created DynamicData\CustomPages\Customer folder.
c. Delete the two code-behind files for List.aspx,, as you’re going to leverage the
code from the existing page template, and change only the HTML.
HTML

Page 23 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

d. Change the page title. Open up the newly copied ListDetails.aspx template and
append the text ““List” to its <h2> element’s content.
<h2><%= table.DisplayName %> List</h2>
e. Define which Customers table columns to display. To do this, switch to
ListDetails design view and find the GridView control used to display the table
data. Click the smart-tag glyph that appears on the side of the control
co to display
the GridView Tasks window. Click Edit Columns to open the Fields window.

Page 24 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
f. Uncheck the Auto-Generate fields option.

g. Specify the columns to display in the table view. To do this, select DynamicField
in the Available Fields list and click Add. Set the DataField value with the table
column name and the HeaderText to a descriptive name. E.g. Set “FirstName” as
the DataField and “First Name” as the HeaderText.
h. Repeat the previous steps for each of the following columns:
 FirstName
 LastName
 CompanyName
 SalesPerson
 EmailAddress
 Phone

Page 25 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

i. Click OK to close the window.


3. Customize Dynamic Note: ASP.NET Dynamic Data provides fields that use your object model to
Data Fields automatically determine the correct control to render to display data. This frees you
from having to write the code to explicitly select controls based on entity column
types. For example, when a DateTime field needs to be rendered, by default the
DateTime.ascx or DateTime_Edit.ascx field is used to render the value.
These controls are provided with the ASP.NET Dynamic data template in the
DynamicData
DynamicData\FieldTemplates directory of your application.
For more information on the provided field controls see Field Template Controls.
Controls
a. To allow the custom control to change images dynamically without doing a full
postback, a reference to the AJAX Control Toolkit assembly needs to be added to
postback
the project. To do this, in Solution Explorer, right-click the project,
project and select
Add Reference
Reference. On the Add Reference dialog box browse to
AspNetDynamicData
AspNetDynamicData\Assets and select the AjaxControlToolkit.dll file. Click
OK to add the reference.

Page 26 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps

b. Add the EmailAddress_Edit, BooleanImage and BooleanImage_Edit custom


controls. To do this, in Solution Explorer, right click FieldTemplates folder
under DynamicData, point to Add and select Existing Item.. In the Add Existing
Item dialog box browse to AspNetDynamicData\Assets and select
EmailAddress_Edit.ascx
EmailAddress_Edit.ascx, BoleanImage.ascx and BooleanImage_Edit.ascx.
BooleanImage_Edit.ascx
Click Add.

c. Add the controls images to the project. To do this, in Solution Explorer,


Explorer right-
click the Images folder under DynamicData\Content,, point to Add and select

Page 27 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
Existing Item
Item. In the Add Existing Item dialog box browse to
AspNetDynamicData
AspNetDynamicData\Assets and select SemaphoreGreen.gif and
SemaphoreRed.gif
SemaphoreRed.gif. Click Add.

d. Indicate to the Dynamic Data framework you want to use the BooleanImage
custom control for the Boolean field instead of the default template. To do this,
open the SalesOrderHeader.cs file under the Model folder and add the following
code (shown in bold) within the SalesOrderHeaderMetadata class:
private class SalesOrderHeaderMetadata
{
...

[UIHint("BooleanImage")]
public object OnlineOrderFlag { get; set; }
}
Note: The UIHint attribute specifies what field template to use when a specific column
is rendered. The framework will look for the control in the
DynamicData/FieldTemplatess directory. If the data control is in edit mode it will
look for a control named with the “
“_Edit” suffix.
e. Add a CustomerMetadata class into the Customer partial class in order to
customize the EmailAdress property. To do this, add the following code shown in
bold within the Customer class.
[DisplayColumn("CompanyName", "CompanyName")]
public part
partial class Customer
{
private class CustomerMetadata
{
}
}
f. Associate the CustomerMetadata class with the Customer partial class by adding
a MetadataTypeAttribute to the Customer class.
[MetadataType(typeof(CustomerMetadata))]

Page 28 of 29
Developing ASP.NET Dynamic Data Web Applications
Tasks Detailed Steps
[DisplayColumn("CompanyName", "CompanyName")]
public partial class Customer
{
private class CustomerMetadata
{
}
}
g. Add metadata for the EmailAddress property to use the EmailAddress template.
To do this, create an EmailAddress property in the CustomerMetadata class and
apply the DataType attribute with the DataType.EmailAddress value to it.
[MetadataType(typeof(CustomerMetadata))]
[DisplayColumn("CompanyName", "CompanyName")]
public partial class Customer
{
private class CustomerMetadata
{
[DataType(DataType.EmailAddress)]
public object EmailAddress { get; set; }
}
}
Note: The DataType attribute specifies additional type information associated with a
data field. Dynamic Data will use it to decide which Template located in the
FieldTempaltes folder will be used to render the field.

Page 29 of 29

You might also like