views:

103

answers:

1

Has anyone successfully used extension methods in data-binding expressions?

Say I have an extension method called "GetName" attached to "MyClass".

In the code behind, I have verified this works:

MyClass myObject = new MyClass();   
MyClass.GetName();

However, in a Web form, I try this:

<%@ Import Namespace="My.Namespace" %>

Then, in the ItemTemplate of a Repeater:

<%# ((MyClass)Container.DataItem).GetName() %>

Visual Studio is cool with this, Intellisense agrees with everything, and the project builds. But when I run it, I get:

Compilation Error
'My.Namespace.MyClass' does not contain a definition for 'GetName'

So, the code-behind will accept the extension method, but not the Web form. I suspect it's a name-spacing issue, but I've imported the same namespace in both places.

+1  A: 

The databinding syntax in aspx/ascx files is notoriously picky. There is a certain amount of parsing that goes on, in particular in this binding area. Look at this example:

This works:

<%# String.Format("{0:C}", DataBinder.Eval("Foo")) %>

But this doesn't:

<%# String.Format("{0:C}", Bind("Foo")) %>

Why? Because while DataBinder.Eval is a real method, Bind is not. Yes, really, it's just a token recognized by the expression binder/parser - it's not actually compiled. I think DataBinder.Eval is probably special-cased for compatibility with ASP.NET 1.1/1.0.

Just to complete the example, the correct way to bind the above expression is to use:

<%# Bind("Foo", "{0:C}") %>

Hope this helps,

-Oisin

x0n