if 语句中的 eval ?
<% if(Eval("SaveDate") != DBNull.Value){ %>
do magic
<%} %>
给出错误:Eval()、XPath() 和 Bind() 等数据绑定方法只能在数据绑定控件的上下文中使用。
我可以写: <%# Eval("SaveDate") != DBNull.Value ?施展魔法 但我需要在 if 语句中做很多 html 魔法。
我知道我应该添加 # 才能使用 Eval,但不确定语法是否正确。
<% if(Eval("SaveDate") != DBNull.Value){ %>
do magic
<%} %>
gives me error: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
I could write : <%# Eval("SaveDate") != DBNull.Value ? do magic
But I need to do lots of html magic in if statement.
I know I should add # in order to use Eval, but not sure about correct syntax.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种解决方案是将内容包装在带有 Visible 值的 runat="server" 标记中,例如
div
可以是任何 HTML 标记,但
也可以使用
。请注意,“do magic”仍然是数据绑定的,因此如果它包含昂贵的代码或在Eval("SaveDate") == DBNull.Value
时可能生成错误的代码,那么它不是一个完美的解决方案。请注意,
Visible="false"
将在生成的 HTML 中省略该标记及其所有内容,这意味着它与style="display:none"
或style="visible:hidden"
,所以不用担心。但是,如果您的“魔术”相当复杂,另一个相当简单的解决方案(有点黑客)是:使用 Repeater(或 FormView),其 DataSource 设置为一个项目的数组(可见)或没有项目(隐藏):
数据源数组的实际内容要么是空(隐藏),要么是您已经绑定到的元素。这可确保您仍然可以在 ItemTemplate 内调用
<%# Eval(...) %>
。通过这种方法,您的“魔术”是一个模板,仅当数据源具有一个或多个项目时才会执行。这是由
ElementIfTrue
负责的。这有点令人费解,但它偶尔可以拯救你。附带说明:将“魔术”打包在用户控件中也可以降低复杂性。您实际上不需要更改 HTML/ASP.NET 标记组合中的任何内容(
<%# Eval("...") %>
即使在用户控件内仍然有效) 。One solution is to wrap the content in a runat="server" tag with a Visible value, e.g.,
div
can be any HTML tag, but<asp:Panel>
and<asp:PlaceHolder>
could also be used. Note that "do magic" is still databound, so it's not a perfect solution if it contains expensive code or code that could generate an error ifEval("SaveDate") == DBNull.Value
.Note that
Visible="false"
will omit the tag and all its contents from the generated HTML, this means that it is very different fromstyle="display:none"
orstyle="visible:hidden"
, so don't worry about that.But, if your "do magic" is reasonably complex, another rather simple solution (a bit of a hack) is: use a Repeater (or FormView) with its DataSource set to an array of one item (visible) or no items (hidden):
The actual contents of the datasource array is either empty (hidden) or the element you were already binding to. This makes sure you can still call
<%# Eval(...) %>
inside the ItemTemplate.With this approach, your "do magic" is a template which will only be executed if DataSource has one or more items. Which is taken care of by
ElementIfTrue
. It's a bit of a mind bender, but it can save you every once in a while.As a side note: packing your "do magic" in a user control can also keep the complexity down. You don't really need to change a thing in your HTML/ASP.NET tag mix (
<%# Eval("...") %>
still works even inside a user control).我通常添加一个受保护的函数,将字符串返回到代码隐藏以生成内容:
在页面上:
在我的班级中:
I usually add a protected function returning a string to the code-behind to generate the content:
On the page:
In my class: