How to use extensions and utility methods in markup?

Ok This is probably a really stupid question, but I’ll ask him anyway ...

How can I use extensions and working methods in my ASP.Net markup? For example, (let's 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 ItemTemplate:

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

I get the following error:

"System.DateTime" does not contain a definition for "ToExampleString", and the extension method "ToExampleString" cannot be found that takes the first argument of type "System.DateTime" (do you miss the using directive or assembly references?)

The page simply cannot see the extension method.

Similarly, how can I make my page layout in a utility class:

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

What steps should I take to get this stuff to work? I assume I'm missing something stupidly obvious?

thanks

+7
markup extension-methods
source share
4 answers
 <%@ Import Namespace="Common.Extensions" %> 

I believe that you can do this for all your markup in the web.config file.

+7
source share

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

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

Or globally in your web.config

 <system.web> <pages> <namespaces> <add namespace="Common.Extensions"/> </namespaces> </pages> </system.web> 

If you just need access to the methods of an open module (or static class), just import the root namespace of the application.

+9
source share

You need to import the namespace at the top of the page:

 <%@ Import Namespace="Common.Extensions"%> 
+2
source share

Namespaces?

You must add the / import directive to your aspx markup

0
source share

All Articles