:::: MENU ::::

Tuesday, April 21, 2009

The ExpressionBuilder is still unknown to a lot of developers that haven’t experienced the sadistic pleasure of localizing a web application. It was introduce in ASP .NET 2.0 and allows you to bind values to control properties using declarative expressions.

I learnt about the ExpressionBuilder when I was doing some research on localization best practices in .NET. The recommendation is to use the specialized ResourceExpressionBuilder that creates code to retrieve resource values when the page is executed.

The ResourceExpressionBuilder is great for localization but what if we want to bind a control’s property to something else? Maybe a value in the Web.config’s AppSetting section. You may have tried something like this: 

<asp:TextBox
id="foo"
runat="server"
text="<%=ConfigurationManager.AppSettings["FooText"] %>"/>

Don’t be embarrassed. We’ve all done it at least once, and we’ve all been greeted with:

Parser Error Message: Server tags cannot contain <% ... %> constructs.

Thankfully there is an ExpressionBuilder that can help. the AppSettingsExpressionBuilder provides access to values in the AppSettings section of the Web.config and we use it as follows:

<asp:TextBox
id="foo"
runat="server"
text="<%$ AppSettings: FooText %>"/>

The ResourceExpressionBuilder and the AppSettingsExpressionBuilder are both derived from the ExpressionBuilder base class. That means we can create our own but I'll leave that topic for another day.

Keep in mind that the ExpressionBuilder only works when it is assigned to the property of a control. So you won’t be able to use it, for example, to pass values to a JavaScript constructor.