There’s a ton of cool stuff coming out with ASP.NET 4.5 and Visual Studio 11. If you haven’t had a chance yet, take a look at my top five list of Visual Studio 11 Designer improvements for ASP.NET 4.5 development, as well as my deeper dive into the VS11 Page Inspector tool. Today however, I want to jump a bit more into code since, so far I haven’t covered too much of that! One of the new ASP.NET 4.5 improvements I’m excited about is the ability to have strongly typed controls. That’s right, you heard me, strongly typed!

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.

Get the Visual Studio 11 Beta

The Warm-up – Creating the Model

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? ;)

Create New EF Model Dialogue

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.

Sample Customers Northwind Model

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.

Upper Body – Binding our Control

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).

Repeater

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:

<ul>
    <asp:Repeater ID="myRepeater" runat="server">
        <ItemTemplate>
            <li>
            </li>
        </ItemTemplate>
    </asp:Repeater>
</ul>

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 (<%# %>)

One-way Binding

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!?

One-way Binding, Entity Intellisense

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:

<ul>
    <asp:Repeater ID="myRepeater" runat="server"
        ItemType="BlogApp.Customer">
        <ItemTemplate>
            <li>
                Company Name: <%# it %>
            </li>
        </ItemTemplate>
    </asp:Repeater>
</ul>

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:

NorthwindEntities db = new NorthwindEntities();
myRepeater.DataSource = db.Customers;
myRepeater.DataBind();

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!

FormView

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.

<asp:FormView ID="myFormView" runat="server"
    ItemType="BlogApp.Customer" OnModeChanging="myFormView_ModeChanging">
    <ItemTemplate>
        Company Name: <%# Item.CompanyName %>
        <br />
        <asp:Button runat="server" Text="Edit" CommandName="Edit" />
    </ItemTemplate>
    <EditItemTemplate>
    </EditItemTemplate>
</asp:FormView>

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.

<asp:FormView ID="myFormView" runat="server"
    ItemType="BlogApp.Customer" OnModeChanging="myFormView_ModeChanging">
    <ItemTemplate>
        Company Name: <%# Item.CompanyName %>
        <br />
        <asp:Button runat="server" Text="Edit" CommandName="Edit" />
    </ItemTemplate>
    <EditItemTemplate>
        <asp:Label runat="server" ID="myEditLabel"
            AssociatedControlID="myEditTextBox" Text="Company Name">
        </asp:Label>
        <asp:TextBox runat="server" ID="myEditTextBox"
            Text=''></asp:TextBox>
    </EditItemTemplate>
</asp:FormView>

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:

protected void myFormView_ModeChanging(object sender, FormViewModeEventArgs e)
{
    NorthwindEntities db = new NorthwindEntities();
    if (e.NewMode == FormViewMode.Edit)
    {
        myFormView.ChangeMode(FormViewMode.Edit);
        myFormView.DataSource = db.Customers;
        myFormView.DataBind();
    }
}

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!

Two-way Binding

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:

<asp:FormView ID="myFormView" runat="server"
    ItemType="BlogApp.Customer" OnModeChanging="myFormView_ModeChanging">
    <ItemTemplate>
        Company Name: <%# Item.CompanyName %>
        <br />
        <asp:Button runat="server" Text="Edit" CommandName="Edit" />
    </ItemTemplate>
    <EditItemTemplate>
        <asp:Label runat="server" ID="myEditLabel"
            AssociatedControlID="myEditTextBox" Text="Company Name">
        </asp:Label>
        <asp:TextBox runat="server" ID="myEditTextBox"
            Text='<%# BindItem.CompanyName %>'></asp:TextBox>
    </EditItemTemplate>
</asp:FormView>

Before you run this, remember to databind just like you did with the repeater:

NorthwindEntities db = new NorthwindEntities();
myFormView.DataSource = db.Customers;
myFormView.DataBind();

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!

GridView

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:

<asp:GridView ID="myGridView" runat="server"
    ItemType="BlogApp.Customer" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="CustomerID" HeaderText="Customer ID" />
        <asp:TemplateField HeaderText="Company Name">
            <ItemTemplate><%# Item.CompanyName %></ItemTemplate>
            <EditItemTemplate><asp:TextBox runat="server" ID="editCompanyNameTextBox" Text="<%# BindItem.CompanyName %>"></asp:TextBox></EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Easy right? Just remember to set the ItemType correctly, as well as databind!

Lower Body – Model Binding

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.

<asp:GridView ID="myGridView" runat="server"
    ItemType="BlogApp.Customer" SelectMethod="GetCustomers"
    AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="CustomerID" HeaderText="Customer ID" />
        <asp:TemplateField HeaderText="Company Name">
            <ItemTemplate><%# Item.CompanyName %></ItemTemplate>
            <EditItemTemplate><asp:TextBox runat="server" ID="editCompanyNameTextBox" Text="<%# BindItem.CompanyName %>"></asp:TextBox></EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

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:

public IQueryable<Customer> GetCustomers()
{
    NorthwindEntities db = new NorthwindEntities();
    var customers = from c in db.Customers
                    select c;
 
    return customers;
}

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.

Cooldown

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!

Try out the Free RadControls for ASP.NET AJAX Today!

About the Author

Carl Bergenhem

is an Enterprise Solutions Consultant at Telerik specializing in the ASP.NET AJAX and ASP.NET MVC products. He has always been interested in web development and has played around with various web technologies since he was a kid. In his free time Carl enjoys soccer, running and playing his guitar.

@carlbergenhem

Related Posts

Comments

Comments are disabled in preview mode.