如何在数据绑定控件中使用 Eval 调用扩展方法
我在 int 类型上有一个简单的扩展方法,因此我可以执行以下操作:
string timeLength = 61.ToTime() // timeLength will be "1:01"
这在代码中效果很好,但我想在中继器模板中使用此扩展方法。 当数据绑定时,我想要执行以下操作:
<%# Eval("LengthInSeconds").ToTime() %>
那不起作用,所以我尝试了:
<%# ((int) Eval("LengthInSeconds")).ToTime() %>
但它仍然不起作用。 JIT 编译器没有看到我的扩展方法,并且页面中确实有正确的导入语句。
我解决这个问题的唯一想法是用 Literal 控件替换 Eval 并在代码隐藏中调用扩展方法,但无论哪种方式,我仍然想知道为什么这不起作用。
谢谢
I have a simple extension method on the int type so I can do the following:
string timeLength = 61.ToTime() // timeLength will be "1:01"
This works great in code, but I want to use this extension method in a Repeater Template. When databinding I want to do the following:
<%# Eval("LengthInSeconds").ToTime() %>
That didn't work so I tried:
<%# ((int) Eval("LengthInSeconds")).ToTime() %>
and it still didn't work. The JIT compiler is not seeing my extension method and I do have the proper import statement in the page.
My only idea for solving this is to replace the Eval with a Literal control and call the extension method in the code-behind, but either way, I would still like to know why this isn't working.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我遇到了同样的问题,最终找到了解决方案。
就我而言,我忘记导入扩展方法类的名称空间。 尽管页面后面的代码包含命名空间,但 aspx-page 却没有。
我刚刚在 web.config 文件中添加了命名空间:
瞧!
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:
and voila!!
看来我得回答我自己的问题了! Asp.Net 使用 .Net 2.0 编译器编译 .aspx、.ascx 模板。 我需要将以下内容添加到我的 web.config 中才能使其工作,
我仍然需要在 Eval 中执行到 (int) 的转换,但这至少对我来说是有意义的。
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
I still have to perform the cast to (int) in the Eval, but that at least makes sense to me.
为我解决这个问题的另一个解决方案(与 Patrik 的类似)是仅导入特定控件或 aspx 页面上的名称空间。
该解决方案更适合我的问题,因为扩展方法仅适用于一个控件中使用的类。
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.
This solution was more appropriate with my problem as the extension methods were only for a class used in the one control.
Eval("LengthInSeconds") 本身有效吗?
Does Eval("LengthInSeconds") work by itself?
命名空间声明是在 web.config 文件中的 Pages 元素下完成的,如下所示:
The namespace declaration is done beneath the pages element in the web.config file like this: