Strongly Typed Data in ASP .NET Web Forms

Strongly Typed Data in ASP .NET Web Forms

In ASP .NET Web Forms you’ve previously had to use strings to specify which properties you’d like to output when databinding, which would probably end up looking something like the following.

<asp:templatefield headertext="Last Name">
    <itemtemplate>
        <asp:literal runat="server" text="<%#: Eval("LastName") %>">
    </asp:literal></itemtemplate>
</asp:templatefield>

In all likelihood it could probably look far less tidy if you’ve ever needed to do any formatting on values you’re about to output to the page. Not to mention the errors you’ll get if you ever rename a property on the model and forget about your web page (because Visual Studio will not warn you about these errors).

In .NET 4.5.1 a strongly typed data feature was introduced for ASP .NET Web Forms. This allows you to specify a type for your data on the binding control which lets you be able to specify properties to bind without the use of strings.

You can make use of this feature by writing code similar to the following.

<t;asp:gridview itemtype="TestWebApp.Models.Person" runat="server">
        <columns>
            <asp:templatefield headertext="Id">
                <itemtemplate>
                    <asp:literal runat="server" text="<%#: Item.PersonId %>">
                </asp:literal></itemtemplate>
            </asp:templatefield>
            <asp:templatefield headertext="First Name">
                <itemtemplate>
                    <asp:literal runat="server" text="<%#: Item.FirstName %>">
                </asp:literal></itemtemplate>
            </asp:templatefield>
            <asp:templatefield headertext="Last Name">
                <itemtemplate>
                    <asp:literal runat="server" text="<%#: Item.LastName %>">
                </asp:literal></itemtemplate>
            </asp:templatefield>
        </columns>
</asp:gridview>

As shown above you can now specify a type for the data you are about to bind using the ItemType property of the databinding control. This lets you then use the Item property in the templates to specify which properties of your model you would like to output (as well as allowing you access to any handy extension methods you may have for formatting output).

This on whole means you know if a change you have made has broken your model binding before runtime, which is definitely a great step forward for ASP .NET Web Forms development.