Sunday, June 9, 2013

Strongly Typed Data Controls in ASP.NET 4.5 with Visual Studio 2012

Before the introduction of ASP.NET 4.5, we used to bind the data to the ASP.NET controls using DataSource property and bind the data using the Eval(expression) function. Eval evaluates the expression and displays the data in the display controls. ASP.NET 4.5 came up with new feature called strongly typed data controls. The benefit of this feature is we can bind the data to the display controls with strong types and we can avoid the exceptions caused by the function Eval(expression) if the expression is not evaluated to a proper value.

This article discusses with the sample code on how the databinding was programmed before ASP.NET 4.5 and in ASP.NET 4.5. This example uses Visual Studio 2012 and the project type created is a simple web site project (Empty web site project). Add a default.aspx webform with code behind if you do not see it in the project.

Before ASP.NET 4.5:

ASPX page:

We used Eval(expression) for binding the data to the individual controls in the list view control below:

<p><u>Normal ASP.NET Binding</u></p>

            <asp:ListView ID="displayData" runat="server">

                <LayoutTemplate>

                    <table id="Table1" runat="server">

                        <tr id="Tr1" runat="server">

                            <td id="Td1" runat="server">Item ID</td>

                            <td id="Td2" runat="server">Item Name</td>

                        </tr>

                        <tr id="ItemPlaceholder" runat="server">

                        </tr>

 

                    </table>

                </LayoutTemplate>

 

                <ItemTemplate>

                    <tr>

                        <td>

                            <asp:Label ID="Label1"

                                runat="server"

                                Text='<%# Eval("ID")%>'>  

                            </asp:Label>

                        </td>

                        <td>

                            <asp:Label ID="Label2" runat="server" Text='<%# Eval("ItemName")%>'>  

                            </asp:Label>

                        </td>

                    </tr>

 

                </ItemTemplate>

 

            </asp:ListView>

 

Code behind for populating the data:

Create a class file called “Product” in a separate file and it will be added in “App_code” folder in the project. This type will be used in the code behind for populating the data of the type “Product”.
 
 
/// <summary>
/// Summary description for Product
/// </summary>
public class Product
{
    public int ID { getset; }
    public string ItemName { getset; }
}
 
/// <summary>
    /// Page Load Method
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
 
        //bind the data to the list view by calling the method PopulateProducts.
        displayData.DataSource = PopulateProducts();
        displayData.DataBind();
 
    }

 

/// <summary>
    /// Method to create new product
    /// </summary>
    /// <returns></returns>
    public IList<Product> PopulateProducts()
    {
        return new List<Product>
        {
            new Product{ID=1,ItemName="Item1"},
            new Product{ID=2,ItemName="Item2"},
            new Product{ID=3,ItemName="Item3"},
            new Product{ID=4,ItemName="Item4"}
        };
    }

 

Code Execution:

Your output should like below:

Normal ASP.NET Binding

Item ID
Item Name
1
Item1
2
Item2
3
Item3
4
Item4

 

Re-writing the code with ASP.NET 4.5:

In the ASP.NET 4.5 there is a new property available called “ItemType” where you can define the type of the Item that is bound in the control. Note, in some of the blogs/articles you see “ModelType” property mentioned instead of “ItemType” as it was available in older versions.

Now add the following code to ASPX page:

<br />
            <p><u>ASP.NET 4.5 Strong Binding</u></p>
            <asp:ListView
                runat="server" ID="displayData2"
                ItemType="Product">
                <LayoutTemplate>
                    <table id="Table1" runat="server">
                        <tr id="Tr1" runat="server">
                            <td id="Td1" runat="server">Item ID</td>
                            <td id="Td2" runat="server">Item Name</td>
                        </tr>
                        <tr id="ItemPlaceholder" runat="server">
                        </tr>
 
                    </table>
                </LayoutTemplate>
 
                <ItemTemplate>
                    <tr>
                        <td>
                            <asp:Label ID="Label1"
                                runat="server"
                                Text='<%# Item.ID%>'>  
                            </asp:Label>
                        </td>
                        <td>
  <asp:Label ID="Label2" runat="server" Text='<%# Item.ItemName%>'>  
                            </asp:Label>
                        </td>
                    </tr>
 
                </ItemTemplate>
            </asp:ListView>

 

In the above code you can observe that the control has a property called “ItemType” which is assigned with the Type that we are going to use to bind the data. In our case it is “Product”. Also, to access the properties of the Type, you need to use “Item.” and the property name will be automatically displayed by the Intellisense. This makes the programmer to bind the strong types to the controls.



Figure: Showing the properties of Type using the Intellisense

Now modify the Page_Load method to bind the data to the second control as below:

 /// <summary>
    /// Page Load Method
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
 
        //bind the data to the list view by calling the method PopulateProducts.
        displayData.DataSource = PopulateProducts();
        displayData.DataBind();
 
        //bind the data to the list view by calling the method PopulateProducts.
        displayData2.DataSource = PopulateProducts();
        displayData2.DataBind();
    }

 

Code Execution:

Your output should like below:

ASP.NET 4.5 Strong Binding

Item ID
Item Name
1
Item1
2
Item2
3
Item3
4
Item4

 

Select Method:

In the above code, we set the data to the controls using DataSource property of the control. We can also bind the data using the Select method of the ASP.NET control instead of setting the DataSource property. Let us see how we can do that now.

Modify your ASPX file to include another control as below:

<br />
            <p><u>ASP.NET 4.5 Strong Binding with Select Method</u></p>
            <asp:ListView
                runat="server" ID="displayData3"
                ItemType="Product"
                SelectMethod="GetValidProducts">
                <LayoutTemplate>
                    <table id="Table1" runat="server">
                        <tr id="Tr1" runat="server">
                            <td id="Td1" runat="server">Item ID</td>
                            <td id="Td2" runat="server">Item Name</td>
                        </tr>
                        <tr id="ItemPlaceholder" runat="server">
                        </tr>
 
                    </table>
                </LayoutTemplate>
 
                <ItemTemplate>
                    <tr>
                        <td>
                            <asp:Label ID="Label1"
                                runat="server"
                                Text='<%# Item.ID%>'>  
                            </asp:Label>
                        </td>
                        <td>
                            <asp:Label ID="Label2" runat="server" Text='<%# Item.ItemName%>'>  
                            </asp:Label>
                        </td>
                    </tr>
 
                </ItemTemplate>
            </asp:ListView>

 

Note in the above code we have set the value for SelectMethod  propery with a Code behind method called “GetValidProducts”. The method “GetValidProducts” has responsibility to get the data to be populated in the ListView control. The method used here should either support IEnumerable or IQueryable type to be able to populate the Type data.

Now let us define a method in the code behind for the same:

 /// <summary>
    /// Method to get the products using IEnumerable
    /// </summary>
    /// <returns></returns>
    public IEnumerable<Product> GetValidProducts()
    {
        //You can add additional criteria for displaying the products by
        //modifying the code in this method
        return PopulateProducts().AsQueryable();
    }

 

As mentioned in the commented code, you can modify the method to include the criteria to check some business logic and refine the data to be returned by the method.

Code Execution:

Now, if you execute the code you should see the data getting populated as below:

ASP.NET 4.5 Strong Binding with Select Method

Item ID
Item Name
1
Item1
2
Item2
3
Item3
4
Item4

 

Note:  Similar to SelectMethod, you can also write methods for Update, Insert and Delete operations.

Final output should look like below:

Normal ASP.NET Binding

Item ID
Item Name
1
Item1
2
Item2
3
Item3
4
Item4




ASP.NET 4.5 Strong Binding

Item ID
Item Name
1
Item1
2
Item2
3
Item3
4
Item4




ASP.NET 4.5 Strong Binding with Select Method

Item ID
Item Name
1
Item1
2
Item2
3
Item3
4
Item4

 

Hope you liked this article!!! Happy coding!!!

No comments:

Post a Comment