Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use extensions and utility methods in markup?

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

like image 719
Leigh Bowers Avatar asked Oct 19 '09 16:10

Leigh Bowers


3 Answers

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>

If you simply need access to methods of a public module (or static class), just import your application's root namespace.

like image 139
David Glenn Avatar answered Nov 02 '22 16:11

David Glenn


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

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

like image 8
Yuriy Faktorovich Avatar answered Nov 02 '22 16:11

Yuriy Faktorovich


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

<%@ Import Namespace="Common.Extensions"%>
like image 2
Pawel Krakowiak Avatar answered Nov 02 '22 16:11

Pawel Krakowiak