views:

170

answers:

4

Ok. This is probably a really stupid question, but I'm going to ask it anyway...

How can I use extensions and utility methods in my ASP.Net markup? For example, (say) I have a DateTime extension method called "ToExampleString()" (contained in the DateTimeExtensions class in my Common.Extensions project) and I want to use it in my markup in the ListView's ItemTemplate:

<ItemTemplate>
    <span><%# ((DateTime)Eval("DateStarted")).ToExampleString() %></span>
</ItemTemplate>

I'm getting the following error:

'System.DateTime' does not contain a definition for 'ToExampleString' and no extension method 'ToExampleString' accepting a first argument of type 'System.DateTime' could be found (are you missing a using directive or an assembly reference?)

The page simply can't see the extensions method.

Similarly, how do I make my page's markup aware of a utility class:

<span><%# ExampleUtility.ProcessDate(Eval("DateStarted") %></span>

What steps do I need to take to make this stuff work? I assume I'm overlooking something stupidly obvious?

Thanks

+3  A: 
<%@ Import Namespace="Common.Extensions" %>

I believe you can do that for all your markups in the web.config.

Yuriy Faktorovich
Thanks Yuriy. I have a "using Common.Extensions" statement in my code behind. Should that be working?
Milky Joe
No, I believe you also need to place it in the markup.
Yuriy Faktorovich
The using statement in code behind allows your code behind class to see the extension methods, but you have to import the namespace in the markup file as well.
Pawel Krakowiak
Thanks for your help.
Milky Joe
+1  A: 

Namespaces?

You should add using/import directive in aspx markup

Alex Reitbort
+2  A: 

You have to import the namespace, at the top of the page:

<%@ Import Namespace="Common.Extensions"%>
Pawel Krakowiak
+4  A: 

You need to import the namespace either at the top of the page as others have said

<%@ Import Namespace="Common.Extensions"%>

Or globally in your web.config

<system.web>
  <pages>
    <namespaces>
      <add namespace="Common.Extensions"/>
    </namespaces>
  </pages>
</system.web>
David G
Thanks for the extra web.config information!
Milky Joe