Strongly Typed Data Controls (ASP.NET vNext Series)

This is the second in a series of blog posts I'm doing on ASP.NET vNext.

The vNext releases of .NET and Visual Studio include a ton of great new features and capabilities.  With ASP.NET vNext you'll see a bunch of really exciting improvements with both Web Forms and MVC - as well as in the core ASP.NET base foundation that both are built upon.

Today's post is the first of a few posts I'll do that talk about some of the improvements coming to Web Forms.  Today's post covers the new support we are introducing for Strongly Typed Data Controls.

Some Background on Data Control Templates

ASP.NET Web Forms introduced the concept of "templates" starting with the very first release.  Templates allow you to customize (or override) the markup emitted from server controls, and are typically used with data-binding expressions.

When using data-binding within a template today, you use late-bound expressions to bind to the data.  For example, below we are using the Eval() helper method to data-bind the "FirstName" and "LastName" properties from a list of objects data-bound to a repeater control:

<ul>

    <asp:Repeater runat="server" ID="customers">

        <ItemTemplate>

            <li>

                First Name: <%# Eval("FirstName") %><br />

                Last Name: <%# Eval("LastName") %><br />

            </li>

        </ItemTemplate>

    </asp:Repeater>

</ul>

When performing 2-way data-binding today, you use the Bind() helper method like so:

<asp:FormView ID="editCustomer" runat="server" >

    <EditItemTemplate>

        <div>

            First Name:

            <asp:TextBox ID="firstName" runat="server" Text='<%# Bind("FirstName") %>' />

        </div>

        <div>

            Last Name:

            <asp:TextBox ID="lastName" runat="server" Text='<%# Bind("LastName") %>' />

        </div>

        <asp:Button runat="server" CommandName="Update" />

    </EditItemTemplate>

</asp:FormView>

One downside with the above approaches is that the calls to Eval() and Bind() are late-bound - meaning you pass strings to represent the property names.  This means you don't get Intellisense for the member names, support for code navigation (like Go To Definition), nor compile-time checking support.

Strongly Typed Data Controls

The next release of ASP.NET provides the ability to enable strongly-typed data templates.  Specifically, we've added the ability to declare what type of data a control is going to be bound to, by way of a new "ModelType" property on data controls.  Setting this property will cause two new typed variables to be generated in the scope of the data-bound template expressions: Item and BindItem.

Developers can use these variables in data-binding expressions and get full Intellisense and compile-time checking support.  For example, below we've set the ModelType on an <asp:repeater> control to be a "Customer" object.  Once we do this we can switch from using Eval("FirstName") to instead use Item.FirstName to reference the property. 

We get full Visual Studio code intellisense when we do so:

image

For 2-way data-binding expressions, we can also now use the BindItem variable and get the same strongly-typed benefits:

<asp:FormView ID="editCustomer" runat="server">

    <EditItemTemplate>

        <div>

            First Name:

            <asp:TextBox ID="firstName" Text='<%# BindItem.FirstName %>' runat="server" />

        </div>

        <div>

            Last Name:

            <asp:TextBox ID="lastName" Text='<%# BindItem.LastName %>' runat="server" />

        </div>

        <asp:Button runat="server" CommandName="Update" />

    </EditItemTemplate>

</asp:FormView>

If we make a mistake while typing, we'll get instant feedback from the IntelliSense engine that something is wrong:

image

Quick Video of the Feature

Damian Edwards has a great 90 second video that shows off using strongly-typed data controls in action.  You can watch it here.

Summary

Support for strongly typed data-controls is a small, but nice, feature that makes working with data-bound expressions easier and cleaner.  In future posts I'll also cover some of the more substantial data improvements we are making to Web Forms in ASP.NET vNext that make data-binding and data-editing even more powerful and easy.

Hope this helps,

Scott

P.S. In addition to blogging, I use Twitter to-do quick posts and share links. My Twitter handle is: @scottgu

68 Comments

  • This is way cool! Wish it had been part of ASP.NET 2.0 onward

  • Great stuff!

    But what's up with this "next release of ASP.NET" stuff?

    "ASP.NET vNext"... "next version of Windows"... next developer-oriented conference that shall not be named PDC... you guys are getting more mysterious by the day :)

  • Wau, this is very useful improvement. Nice inspiration from MVC. Thanks for this.

  • more or less we are going the MVC way..

  • Nice!

    I have one feature request: generics support in templates.

    That would be a VERY nice feature. So you could do something like this:


    <ItemTemplate>
    ....
    </ItemTemplate>
    <ItemTemplate>
    ..........
    </ItemTemplate>

  • ohhh... i was just planning 2 write on this tonight..

    Where can we download Visual Studio vNext for experiments?

  • Hello Scott,

    I see the asp:Repeater control has the ModelType property. Who does own it (some interface, of base class)?
    Because I do not see this property for the asp:FormView control, and it seems to me that Intellisense for the control does not work.

    Does Intellisense work for data types which are static (I mean the Model has a predefined public properties that are known at compile time)?

  • Saw a preview of this in one of the MIX videos. I try to avoid Web Forms these days but I eagerly reported this upcoming feature to some colleagues that haven't switched to MVC yet, and they were very excited. It's an excellent idea.

  • I hope, there will be support for "Find All References" MSVS command too.

  • You can already get Intellisense in ASP.NET v2+ if you use a casted Container.DataItem in your control template instead of using Eval(...)

    e.g. vs

    Admittedly, it's not as pretty but you can use it right now.

  • Hi Scott,

    are you investing equally to Web Forms and MVC? Would be interesting to know which one will win in the future since I think they are overlapping :)

  • Great!! That's what I've been waiting for. IntelliSense for VC++, too since I've tried and uninstalled SlickEdit.

  • @Nandip,

    >>>>>> Where can we download Visual Studio vNext for experiments?

    We don't have a download just yet - we will in the future though :)

    Thanks,

    Scott

  • @Vidar,

    >>>>>> I have one feature request: generics support in templates.

    We have looked at implementing that - although the cost is unfortunately high so we have not done it just yet. I agree it would be cool to have!

    Thanks,

    Scott

  • @Vest,

    >>>>>>> Because I do not see this property for the asp:FormView control, and it seems to me that Intellisense for the control does not work. Does Intellisense work for data types which are static (I mean the Model has a predefined public properties that are known at compile time)?

    Good catch - I must have accidently cut that when I entered it (the danger of text instead of image screenshots!). The FormView control does indeed have a ModelType property and you'd need to set it to get intellisense.

    Hope this helps,

    Scott

  • @Anssi,

    >>>>> are you investing equally to Web Forms and MVC? Would be interesting to know which one will win in the future since I think they are overlapping :)

    We are investing pretty heavily in both. There a ton of awesome features in each of them. :)

    Thanks,

    Scott

  • Nice! And so much more readable. And just the shear joy of not having to replace the attribute quotes to single quotes everytime...

    @Vest:
    The ModelType property only specifies which kind of items you expect in the data source, eg. a list of Customers or Departments.
    This has nothing to do with static data types as you cannot create a collection of static types, right?

  • Cool! I don't know what took you so long to do this one. I've been writing "OnItemDataBound" events for this very reason. Now can we please get the same love for the ObjectDataSource control. It is absurd to pass type names and method names as strings instead of delegates for example. With the Eval/Bind issue solved ObjectDataSource's dependece on strings and the weird behaviour of the DataPager when you set pagesize and similar properties from code behind are my greatest problems with Web Forms.

  • Great news Scott

    Have ye had time to fix the bug where a custom templated control refuses to render in the designer?

  • Hi Scott
    Is there any chance we can use this with asp.net 4.0 Service Pack(any version) ???

  • @Scott:
    >>>>>>>We don't have a download just yet - we will in the future though :)

    It means that other blogger cant write fresh series on the new feature of vNext(Model binding, Asyn Patterns in ASP.NET, Querystring/Form/Viewstate member with method parameter,vNext CSS editor, etc.) even if they know about it. First time Microsoft's policy annoyed me... :( Hope 2 see preview release if it is available under any circumstance..

  • @Vidar,

    >>>>>> I have one feature request: generics support in templates.

    >>>We have looked at implementing that - although the cost is unfortunately high so we have not done it just yet. I agree it would be cool to have!

    Even if you don't add support for it in the built-in controls, it would be nice if it could be supported for those of us that write custom server controls, so can we make the decision if the performance penalty is too high.

  • I've been waiting about 10 years for this!

  • Where's the "Like" button? VERY good feature set here...I dig.

  • Looking more and more like Flex all the time...

  • I saw the question about WebForms and MVC: this seems to be a step toward a hybrid WebForms/MVC platform. I think as you guys share more, you're going to want to move closer to a real hybrid system that you already started tinkering with when you added routing to WebForms. Imagine taking the strengths of both platforms and merging them into a single development unit. MVC with WebControls and maybe the occasional server event? Why not?

  • It is slowly becoming like advanced XAML programing.

  • I'm not sure if this the same thing that you responded to @Vidar about, but I'd love to just have support for generic controls. I'm thinking that you could do something like:



    Where SomeControl would be defined as:

    public class SomeControl : Control { }

    And in the generated code, the markup would translate to:

    protected SomeControl SomeControl1;

    The basic gist is to add in a special property like runat="Server" that would allow you to specify the T in Control or T1 and T2 in Control. Have you guys talked about anything like that?

  • @Goudinov There is a hybrid MVC Webforms Nuget package put out by Scott Ha Ha

  • Gr8 improvement , one of "must to" features I was wating for years.

  • Awesome new feature! I look forward to a CTP.

  • thanks.
    it's very nice & useful.

  • Its realy good article!!

  • Late but good.

    thanks.

  • A feature I've longed missed in web forms since starting some development in MVC is data annotation validation. Is this a step in the direction of enabling data annotation support for web forms?

  • @Stilgar,

    >>>>>> Cool! I don't know what took you so long to do this one. I've been writing "OnItemDataBound" events for this very reason. Now can we please get the same love for the ObjectDataSource control. It is absurd to pass type names and method names as strings instead of delegates for example. With the Eval/Bind issue solved ObjectDataSource's dependece on strings and the weird behaviour of the DataPager when you set pagesize and similar properties from code behind are my greatest problems with Web Forms.

    I'll be doing some more blog posts on data-binding next week. We have lots of improvements coming there that I think you'll like. :)

    Thanks,

    Scott

  • @Jonathan,

    >>>>>>> Have ye had time to fix the bug where a custom templated control refuses to render in the designer?

    Can you send me email (scottgu@microsoft.com) with details of this issue? We can then follow-up and investigate.

    Thanks,

    Scott

  • @Vidar,

    >>>> Even if you don't add support for it in the built-in controls, it would be nice if it could be supported for those of us that write custom server controls, so can we make the decision if the performance penalty is too high.

    The challenge with the implementation is mostly within the parser, and how the code Intellisense engine within VS works. So unfortunately we can't easily do this work for any controls (either our own or custom ones). We are going to keep looking at it for the future though.

    Hope this helps,

    Scott

  • @Goudinov

    >>>>>> I saw the question about WebForms and MVC: this seems to be a step toward a hybrid WebForms/MVC platform. I think as you guys share more, you're going to want to move closer to a real hybrid system that you already started tinkering with when you added routing to WebForms. Imagine taking the strengths of both platforms and merging them into a single development unit. MVC with WebControls and maybe the occasional server event? Why not?

    You'll see more unification of concepts in upcoming posts. There are some nice data-binding improvements we are adding to WebForms (that I'll blog about next week) that make some concepts very similar to MVC.

    Hope this helps,

    Scott

  • @Fredrik,

    >>>>>>> A feature I've longed missed in web forms since starting some development in MVC is data annotation validation. Is this a step in the direction of enabling data annotation support for web forms?

    I'll be blogging more about the new Web Forms data-binding features next week. I think you'll like what you see :)

    Hope this helps,

    Scott

  • I'm totally confused about my future.
    I'm ASP.NET WebForm-based programmer. I'd mastered it for years.
    Then come the MVC and Silverlight.
    I took Silverlight path. And then... what you know....

    Now if WebForm is going to be more "modern" than before
    maybe I'll considering switch back to WebForm again.
    I'd love to have you improve GridView to make it freezable,
    true AJAXable editing and paging, and works with Data Annotations.
    Give us some Layout control that use HTML5 to create Silverlight-Like layout.
    Smarter Bindings. Smarter Image control.
    Facilitate HTML5's offline functionality.
    If you can provide me those.
    Maybe I don't need to go Silverlight anymore.
    Pity to my XAML investment. I hope you bring most we have learned from Silverlight
    into ASP.NET vNext too and don't let it wasted.

  • cool feature....again making it like Silverlight bound controls................

  • Nice features for webforms...

  • What about WPF and Silverlight that has the some sort of issues?

  • I was really missing this feature :(

    Thanks
    Amer

  • Will Visual Studio vNext produce StyleCop compliant code out of the box?
    E.g.
    1) using statements inside the namespace instead of outside the namespace
    2) .cs files having headers with file name, year and company name filled in.

  • Great stuff!
    Will there be some porting to previous versions, at least to ASP.NET 4.0?? These features are killer features!

    Thanks.

  • Can we fast track this!!!

  • Our internet application uses WebForms > Business Data Layer > SQL Stored Procedures > SQL Server 2005 for all data operations.
    Obviously (or presumably) you can't create a data model without running the procedure to see the results schema. Therefore, can we ask that the creation of a datamodel is simple and painless...??!?

  • Finally...some new features that really matter and help productivity. Thanks!!

  • One thing that I've wished for in the past is that classes such as Page had a DataContext property like there is in WPF controls. So that say you had an instance of a Person class, you could assign it to the pages DataContext property and then bind like Eval("Name") instead of having to define your own instance variable and bind against that. Hopefully, there will be something similar to ASP.NET MVC where you can define a strongly typed Page too.

  • This is cool! But can this work with anonymous model type?

  • Great - in actual .NET it was very lack of this.

  • I implore that if you're going to address design-time binding, make sure to go "all the way". It seems like too many features added to the asp.net designer are cool in concept, but then when you actually try to use them, you end up having to rewrite it yourself to get all the features you want. Binding is probably the best example of that.

    For one, give the developer access to the binding information. Right now a developer has no way to get to binding information, so, for example, if you want to bind both on the server side and the client side, you can't use the design-time binding information to generate client-side bindings. Another example I saw in the comments is support for generics... that seems absolutely essential.

    You catch my drift... please don't add just a few new scenarios and then close it all up so we can't do anything with it. I understand that this code you're writing is part of the page parser and goes into the auto-generated control code (as opposed to the code-behind), but you should still be able to give us binding and type information through the ITemplate interface property or by some other means.

    By the way, I am able to get this behavior now by creating strongly typed template classes for each data type I wish to use. This is very clumsy in the setup (as you need a class for each type you want to bind to), but it does allow for strongly-typed binding using the exact syntax you've described.

    That said, I'm very glad you're adding this. I agree that this is a sorely missed feature.

  • It would also be very cool to add data templates like WPF has. You could create one template for type X and another template for type Y, and then the control picks which template to use based on the type of the bound item.

  • Sweet! I've been using a solution with a ControlBuilder, TypeDelegator, PropertyDelegator and a generic container class to get strongly typed one-way binding working, but this looks much better.

    I presume we'll be able to enable our own controls to take advantage of this new support? Will you be covering that in a future post? :)

  • Hi Scott,

    altought it is good news, this feature fits perfectly with the repeater, but it does not fit so well in the Grid, for example. The databounds columns, for example, are still written as plain strings...

  • This is really cool.

  • Is this does not effect the performance of the site

  • Love the new stuff Scott. I have only been hard core coding for about 6 months, after a 2 year learning curve. One thing I'd love to see, might have already been suggested, and this featue sort of overlaps, is intellisense tied directly to web app database. Writing parameterized queries for example I always end up opening the server explorer to get field names. Actually anytime I am in the code behind, would be nice to simply pluck the table fields without having to look them up.

  • Cool feature..
    Thanks Scott.

  • Hello;

    Can any one tell me that the Intellisense, which shown here and video. Is it only for Microsoft releated people? or is it there with Visual Studio 11 Developers Preview?
    becoz i am doing the same thing in VS11 D P and i was not getting this "ModelType" property Intellisense.

    Steps are as follows:
    1)I have open a new WebSite & kept one Repeter Control on default.aspx
    2)Created a class. eg."Student" with two properties public string say "FirstName" and "LastName".
    3)I have created a method say public BindingList GetData()
    3)I was calling this method in page load and binding to Repeter.

    please help me becoz i also want to see this feature in my desktop.
    thanks

  • debug uses a lot of time. this feature really saves a lot of time, less frustration from errors. thank Scott.

  • I agree with what Tiffany said about being able to do two-way binding to a single instance of an object without having to use FormView. I always thought the way ASP.NET handled this was lame. IMHO, ASP.NET Web Forms should work more like WPF where you have ValueConverters. In Java-land, JSF works this way also.

  • Have the team spent the time to go back through all the major controls and fix the known major issues i.e. ObjectDataSource hard coded datetime culture bug, stripping out all the inline css without the use of css friendly control adapters, reliance of javascript from all the ones listed in Microsofts own documentation, Insert support (and just a general spruce up of gridview (i.e. seperate paging, native support for sorting/paging IEnumerable, how about support? How about adding the ability to specify the type without having to ((WebControl)input).Attributes["type"] = "password" for example so we can get HTML5 browser support.

  • Talking about templates - it would be nice to include a template selector (like in WPF).

  • Nice post and great new feature. I can finally no need to remember the whole class property when use GridView.

  • Where's the "Like" button? VERY good feature set here...I dig.

Comments have been disabled for this content.