Strongly Typed Data Controls in ASP.NET 4.5

In this article, we will explore a new feature introduced in ASP.NET 4.5 called Strongly Typed Data Controls. We will see why we should care about this new feature and how can used instead of the Eval function in ASP.NET.

Also read Avoid DataBinder.Eval in ASP.NET and improve Performance

For this demonstration, I am using Windows 7 and Visual Studio 2012.

Let’s first create a blank web site using Visual Studio 2012 with the name “StronglyTypedDataControlDemo” as shown below –

create-site

Now let’s add a new item which uses web form in our blank website with the default name “Default.aspx”. Now add a Repeater control in our “Default.aspx” as shown below –

repeaterinitialcode

If you observe the code, we have a “Header Template” and “Footer Template” as well we our “Item Template”. The “Item Template” is currently blank. Let’s design the item template as it’s usually done –

item-template-code

Now let’s add a new database “ExampleDB” and add a new table in the same database with the name “Customers” with following columns specifications –

image

Add a new class, which is “LINQ to SQL” in our web site with the name “CustomerInformation.dbml” as shown below –

linqdbml

Now drag and drop customers table into our "CustomerInformation.dbml".
Add the following code into our code file -

pageloadcode

Run your web site and you will see the output as shown below -

final1
Let's change the field name which we have passed to our "Eval" Expression and misspell it. After this change, compile the application and you will see the application gets compiled successfully.

wrongcontname

If you observe, I have misspelled the "ContactName" to "ContacName" and my web site still gets complied. But if you run the web page, you will get an error as shown below -

runtimeerror

To avoid similar issues where developers may misspell field names, ASP.NET 4.5 has come up with Strongly Typed Data Controls.

Now let's set a new property in our repeater control which is "ItemType" to "Customer" and replace the "Eval" expression with the "Item.ContactName" as shown below -

Note: Observe the  intellisense when you set ItemType as well as when say Item followed by a dot(.) -
itemtype
and
item

Now replace all Eval, with Item.ContactName, Item.State and Item.Country respectively and run your web page and you should see the same expected output as shown below -

final1
Now try to misspell the column/field name, and you will instantly see a red line below the field and if you compile the application, you will get errors in "Error List" window as shown below -

error

How very convenient!

Summary - In this article, we have seen how to use the new Strongly Typed Data Controls compared to Eval expressions in ASP.NET 4.5.

Download the source code (GitHub)




1 comment:

Maile Kinney said...

Here you provide the demo from which I could gain more from basic to advance.