Why can I not combine if and eval? And whats the best alternative?
In a Asp Net data bound control one can use the nice Eval() syntax:
<div><%# Eval("MyProp") %></div>
but it's not possible to combine with a conditional statement is it?:
<% if (Eval("MyProp")!="") { %>
<div><%# Eval("M开发者_开发技巧yProp") %></div>
<%} %>
Would be nice to have that option.
So - my option is to put part of the markup in CodeBehind. I really liked to keep it out of there. Any other possibilities?
<div runat="server" visible='<%# !String.IsNullOrEmpty(Eval("MyProp") as string) %>'>
<%# Eval("MyProp") %>
</div>
Edit 2010/9/30
Now that I have a little time I feel like I should expand on my answer. Especially considering that the question is a duplicate that already has a better answer than my original. So I will tackle the first part of your question:
Why can you not combine if and eval? The reason is that <% ... %>
code blocks are executed during the render phase of the page lifecycle. ASP.NET puts your code (the if statement in this case) into a function, then passes that function as a delegate to SetRenderMethodDelegate. The problem is that Eval evaluates your expression "MyProp" on the object returned by Page.GetDataItem. Page.GetDataItem is a bit of magic that only returns a value if there has been a call to DataBind earlier in the call stack. By the time the render phase comes around, all the data binding has finished. Hence when you call Eval, which implicitly calls Page.GetDataItem, the following error is thrown: "Databinding methods [...] can only be used in the context of a databound control."
So <% ... %>
code blocks won't work, but what about <%# ... %>
code blocks, a.k.a. data-binding expressions? Data-binding expressions do run in the desired part of the page lifecycle—within a call to DataBind. However, the operative word here is expression. An if
statement is not an expression. Anything you throw between <%# ... %>
will be evaluated by the compiler as an expression. If you put a statement in there, the compiler will throw an error.
Hence we arrive at the idiom of calling Eval in a data-binding expression on the Visible property of a control. Eval is compatible with data-binding expressions; writing an expression is sufficient to assign the value of a property; and the Visible property is able to achieve an effect similar to that of using an inline if
statement.
Final tip: if you ever end up in a situation where you don't have any existing control to naturally add a Visible condition to, you can always use <asp:PlaceHolder>, a control that doesn't add any tags to the markup.
It's because Eval("MyProp")
returns object and you cannot compare object to string. You might need to cast it to string (if MyProp
is of type string of course).
<% if ((string)Eval("MyProp") != "")
{ %>
<div>
<%# Eval("MyProp") %></div>
<%} %>
or
<%# (string)Eval("MyProp") != "" ? string.Format("<div>{0}</div>", Eval("MyProp")) : "" %>
精彩评论