Why am I so excited about controls being strongly typed? How many times have you written a Eval() or Bind() statement and accidently screwed up the spelling of an entity or a field name? Not to mention having to either user a declarative DataSource control or use the DataSource property and DataBind() function in the code-behind. Thanks to strongly typed controls you can now utilize intellisense to ensure that you are binding to the correct field in your model, as well as take use of that awesome model binding that can be found in ASP.NET MVC.
Are you excited yet? Well mix that protein shake, prepare your most powerful music playlist (Katy Perry and Ke$ha anyone!? Hehe, just kidding [or am I?] ;)), and let’s take our ASP.NET controls to the gym!
Hold on, wait! Before we start we need to take the ultimate suppliment: the latest version of Visual Studio - Visual Studio 11. Download the beta today right here. Guaranteed to get those muscles ready for the hard work ahead.
What is a strongly typed anything without a type? We first need to go ahead and create the model that we want to use in our ASP.NET controls. In my case I figured I could take use of the Entity Framework and create a model that way, since that’s something easy for everyone to follow along with. Keep in mind that I’m using Visual Studio 11 here, so if any of the screenshots look different (read: Metrofied) it’s just my version of Visual Studio :)
So, let’s just go ahead and add a new model by right-clicking on our solution and going to Add > New Item…. Since I’m planning on connecting to Northwind (specifically the customers table) I’ll call my model NorthwindModel – pretty original, eh? ;)
From here I’ll just go ahead and generate my model from the database, set up my connection string (calling it NorthwindEntities - again, groundbreaking naming convention). I’ll wrap everything up by selecting the Customers table from Northwind and assigning NorthwindModel as my model’s namespace. Once I’ve gone through the wizard I should be greeted by the Entity Framework design area.
There we go, a shiny new Model! We could of course also just create our own entity using code and work with everything that way if we’d like to as well.
So now that we have the model we’re all kinds of excited to actually have data on our page, so let’s get started right away! I’m going to take a look at the Repeater, FormView, and GridView ASP.NET controls that should be in all ASP.NET toolboxes. If for some reason they aren’t there, make sure you’re actually viewing your .aspx page and reset your toolbox (right-click in the toolbox and select Reset Toolbox from the context menu).
The repeater code is pretty simple actually; all I want to do is display every company name from the Customer’s table as a list item in an unordered list. To do this (without the strongly typed portion) I would just have to do the following:
Now, how do we make this strongly typed? Well with ASP.NET 4.5 a lot of the traditionally databound controls have an “ItemType” property. Within this property all you have to do is point to the particular model that you’re working with. In my case I called this application BlogApp, so I would need to do BlogApp.Customer to get my customers. If I wanted to use my Person entity from above I would just use BlogApp.Person.
Once I’ve done this I can go ahead and use the Item object inside of my WebForms markup whenever I want to get a hold of a field from that model. This is for one-way binding, it is slightly different for two-way (which I’ll cover in a second). We still use the traditional <%# %> syntax though, so it’s not a huge amount of change to the way we already operate (which is great!). Take a look at the following two screenshots to see how it works.
First I set up my binding statement (<%# %>)
As you can see Item pops up via intellisense (yay!) If you take a note at the helpful tooltip you can even see what type it is (in this case BlogApp.Customer).
Once I’ve typed Item I just have to hit the good old “.” key to get intellisense across the Customer entity that I have. Don’t you just love it when you don’t have to rely on your own spelling!?
We can immediately see how useful this is. Traditionally you either wrote Eval() and had to manually type a string in, hoping that you had everything spelled (and capitalized!) correctly. Now intellisense takes care of all of that for you. Even if you do start to type something yourself and it’s not available in our entity VS11 will tell you! :)
This leaves us with the following code:
Now if you want to display this on your page you can’t just go hitting “View in Browser” and see the results. Why? Well the data isn’t actually bound to the control yet. All we’ve done here is say “this is the type that you should be, and these are the fields that are available”. We haven’t actually provided the data itself to the ASP.NET Repeater control. This is easy enough though. In the code-behind we could just do something like this in the Page_Load event handler:
Now if you run the application you will see a full list of the company names in Northwind’s customer table all as list items in an unordered list!
The FormView is another control that can be strongly typed now. The reason I wanted to show this off is just because you can see how we can do two-way binding, not just one-way as we did above. So, let’s define a FormView that displays the CompanyName field like with our Repeater, and let’s leave the EditTemplate blank for now.
Nothing too special. In fact, we’re not really using the FormView to its full potential (or even a sliver of it!) but this is just a quick example after all ;)
Where it gets interesting is when we define the EditTemplate. So, let’s first give ourselves a label control and associate that with a TextBox, which we will use to edit the CompanyName field in a bit.
You might’ve noticed that I decided to subscribe to an event called [event name]. This is just to ensure that when I press the Edit button in my ItemTemplate the FormView actually goes into Edit mode. Here’s the C# associated with that event:
You might have noticed that I left the Text property of the TextBox blank, well that was intentional, so don’t rush to the comments section right away ;) The reason I left this blank is because I wanted to show how you can set up that two-way binding I mentioned. When we did the one-way binding with the Repeater we used the Item object, but when we want to do two-way binding we use BindItem instead. This comes up just as easy in intellisense, so there’s no need to worry!
And similarly, when we hit the “.” key we get intellisense for all of the fields across this particular entity. So, if we want to use CompanyName again we get the following code:
Before you run this, remember to databind just like you did with the repeater:
Once that’s taken care of you can feel free to view this in your browser. Upon hitting enter you should be granted with a TextBox that contains the CompanyName value. If this was bound to a SQLDataSource, and we set up the proper update commands, anything you changed in this EditTemplate would be reflected back in the database!
The GridView has pretty much the same code as the FormView, where you need to define a specific ItemTemplate as well as EditTemplate for each column. Here’s an example using the Customer model I used above:
Easy right? Just remember to set the ItemType correctly, as well as databind!
Now Model Binding is a little bit different than what we were doing above. This actually takes after the model binding found in ASP.NET MVC, and also takes some concepts from the ObjectDataSource. The main difference really is that instead of setting the DataSourceID (or DataSource and then .DataBind() in the code-behind) you specify a Select, Update, and Delete function that the control can call. Now for this example I’m only going to use Select, but it should give you the overall idea. Take a look at this GridView code, which is pretty much identical to the one I had above.
Notice the difference? Next to ItemType I’ve assigned a function name to the SelectMethod property. If I go to my code-behind I’ve added the following:
As you can see, this just queries the Customers table and returns all entries, so it’s nothing too advanced. However, the great thing is that the control will call this whenever it needs to select data. This means on initial page load and other events such as paging (useful with the GridView) – all without having to use declarative data sources on your page. The same model binding that was previously only found in ASP.NET MVC can now be found in ASP.NET Ajax as well! As I mentioned you can define such functions for Deleting and Updating as well. Here I returned an IQueryable, but you should be able to take use other interfaces such as IEnumerable as well.
So there you have it. You just took your ASP.NET 4.5 controls to the gym and got them buff my friend! Having the ability to take use of intellisense when doing one- and two-way binding definitely can help with a lot of frustration when just typing out field names using strings (I cannot tell you how often that happens to me!). Additionally, the ability to take use of a similar model binding to what you find in ASP.NET MVC brings over more of that connection with your entities, such as the ones I generated here with the Entity Framework. It’s pretty exciting stuff, and definitely a step in the right direction for creating great ASP.NET WebForms applications in VS11!
Subscribe to be the first to get our expert-written articles and tutorials for developers!