How to call extension methods using Eval in a databound control

混江龙づ霸主 提交于 2019-12-03 11:08:44

I had the same problem, and eventually found the solution.

In my case I had forgot to import the namespace of my Extensionmethod-class. Even though the code behind page included the namespace, the aspx-page did not.

I just added the namespace in the web.config file:

<pages styleSheetTheme="Default">
  <namespaces>
    <add namespace="MyNameSpace"/>
  </namespaces>

and voila!!

Looks like I get to answer my own question! Asp.Net was compiling the .aspx,.ascx templates using the .Net 2.0 compiler. I needed to add the following to my web.config to make it work

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
    </compilers>
  </system.codedom>

I still have to perform the cast to (int) in the Eval, but that at least makes sense to me.

Another solution which solved it for me (which is similar to Patrik's), is to just import the namespace on that specific control or aspx page.

<%@ Import Namespace="My.Namespace.Containing.MyExtensions.Class" %>

This solution was more appropriate with my problem as the extension methods were only for a class used in the one control.

Does Eval("LengthInSeconds") work by itself?

The namespace declaration is done beneath the pages element in the web.config file like this:

<pages styleSheetTheme="Default">
      <namespaces>
        <add namespace="MyNamespace"/>
      </namespaces>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!