Strongly Typed Data Controls In Asp .Net 4.5

Jul 26, 2013
Download Source

One of the cool feature of Asp .Net 4.5 is Strongly typed data controls. In past when we worked with Asp .Net applications we used controls like GridView, Repeater etc. When defining the ItemTemplate for these controls we had to use the 'not very intuitive' Embedded code block technique. And to add to that we had to pass the property names as blind strings hoping that when objects are bound to these controls they will have relevant properties.

Following is an example of one such binding.

Old Way Of Binding Data

One of the major enhancement in Asp .Net 4.5 is strongly typed data controls. So what exactly this means? From Asp .Net 4.5 if you are defining any Data controls you will be able to Define the Type of object that is going to be bound to this Control. And your control being completely aware of the incoming Type, when defining the ItemTemplate you can pass the actual property names instead of just passing these property names as string.

Let's see how.

First we will create a new empty Asp .Net Web Application project.

Cretae Project

We will add a simple ASPX page named Userlist.aspx and on that page we will define the repeater control as below.

Add Aspx Page

Next, we will add a folder called Model and in that folder we will add a new class called User. Essentially what we want to do is create a List object and bind it as the DataSource of a Repeater control.

Add Folder

Go ahead and add following properties to our User class.

User model class

Now, on the Page_Load event of our Userlist.aspx age we want to bring down User data from the database. For the demo purposes I will just be using For loop to generate some dummy data.

User model class

Now with the DataSource property setup correctly we will have to define the ItemTemplate for this Repeater control. And that's where we will be using new Strong Typing feature of Data Controls.

If you see, the first thing we did is defining ItemType property on the Repeater. That makes our control completely aware of the type of data it will be bound to. Next, when you are inside an actual item template you can use full Intellisense support. That way you will not make any mistakes since you strong typing the property name you are binding to the ItemTemplate element.

Go ahead and run the application, the repeater is working as expected but this time being completely aware of model being bound to it.

User model class