JumpStart # 14–Strongly typed Data Controls in ASP.Net 4.5

Before looking at the code, Read about – What is JumpStart?

ASP.NET 4.5 provides an ability to declare the data type of the data that a control is bound to throught ItemType property. When we set this property, two new typed variables are available in the scope of data-binding expressions: Item (One Way binding) and BindItem (Two Way Binding).

In previous versions, Data binding expressions are evaluated at runtime using reflection and bind data, which is not only developer nightmare but also encourages more data shaping problems.

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a list of persons as a source to Repeater
        List<Person> _persons = new List<Person>();

        _persons.Add(
            new Person()
                {
                    Name = "Rami",
                    Email = "r@abc.com",
                    Contacts = new List<string>() { "123-456-7890", "987-654-3210" }
                });

        _persons.Add(
            new Person()
                {
                    Name = "Ramilu",
                    Email = "ra@abc.com",
                    Contacts = new List<string>() { "321-654-0987", "789-456-0123" }
                });

        Repeater1.DataSource = _persons;
        Repeater1.DataBind();

    }

    public class Person
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public List<string> Contacts { get; set; }
    }
    
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Repeater ID="Repeater1" runat="server" ItemType="Person">
            <ItemTemplate>
                <ul>
                    <li>Name : <%# Item.Name %></li>
                    <li>Email : <%# Item.Email %></li>
                    <ul>
                        <asp:Repeater ID="Repeater1" runat="server" DataSource="<%# Item.Contacts %>">
                            <ItemTemplate>
                                <li>Phone : <%# Container.DataItem %></li>
                            </ItemTemplate>
                        </asp:Repeater>
                    </ul>
                </ul>
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

 

Output -

StringTypesDataControl1

You may also like...