Sunday, June 5, 2011

Parse data-binding expressions in typical and atypical ways

Most ASP.NET developers bind data items to the page in the way like below:
<%# Eval(Container.DataItem, "SomeProperty")%>
But there is a less known technique to achieve the same.
The Page object contains a method to retrieve the data item at the top of the data-binding context stack - GetDataItem(). In other words, this method returns a reference to the successive item, to which the Page object moves while iterating through bound data sources.
How can you leverage this functionality? In your page’s code-behind, add a property that returns a string (later you will want to insert this string into your markup):
protected string SomeProperty
    object dataItem = 
        this.GetDataItem(); // dataItem == Container.DataItem
    object _SomeProperty = 
        DataBinder.Eval(dataItem, "SomeProperty");
    //some processing goes here
    return _SomeProperty as string;
In the markup, add a binding expression that references the property you have created:
<%# SomeProperty %>
This is how the pieces of the solution are put together.


Although both approaches can yield the same results, they are used under different scenarios. The two-piece scheme is especially useful when you need to process a property of a data item before adding it to the markup. On the other hand, if you need to output that property as is, the parsing that is fully defined in your markup would be a simpler option.

No comments: