问题
I'm new to ASP.NET, and I'm trying to figure out how to only show a chunk of code in the .aspx file if a value is not null or whitespace. Here's what I have, within a DetailsView
:
<asp:TemplateField HeaderText="Phone">
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPhone" Text='<%# Bind("Phone") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<a href="tel:<%# Eval("Phone") %>">
<i class="icon-phone"></i>
<%# Eval("Phone") %>
</a>
</ItemTemplate>
</asp:TemplateField>
I want to conditionally hide the whole a
tag if Eval("Phone")
is null or whitespace. I would prefer to do this all in the markup, as opposed to doing something in the code-behind.
回答1:
David's answer pointed me in the right direction:
<asp:HyperLink runat="server" NavigateUrl='tel:<%# Eval("Phone") %>'
Visible='<%# !string.IsNullOrWhiteSpace(Eval("Phone").ToString()) %>'>
<i class="icon-phone"></i>
<%# Eval("Phone") %>
</asp:HyperLink>
回答2:
First, change it to an ASP:Hyperlink control. The html A tag doesn't have a nive convenient Visible property like the ASP:Hyperlink control does.
Then you can set the visibility declaratively.
<asp:HyperLink runat="Server" NavigateUrl='tel:<%# Eval("Phone") %>' Text='<%# Bind("Phone") %>' Visible = '<%= DataBinder.Eval(Container.DataItem("phone").ToString().Trim() == "" %>' />
回答3:
I am afraid you can't do the conditional if within an eval statement. Instead, just wrap the simple eval with the function but To handle this situation i usually add a method called NullHandler(). Consider the function below.
protected string NullHandler()(object gridViewObject)
{
if (object.ReferenceEquals(gridViewObject, DBNull.Value))
{
return "Empty";
}
else
{
return gridViewObject.ToString();
}
}
then you can put like below
<asp:Label ID=”phoneLbl” runat=”server” Text=’<%# NullHandler(Eval(“Phone”)) %>’>
Hope this help.
来源:https://stackoverflow.com/questions/11041488/how-to-conditionally-show-hide-link-in-detailsview-itemtemplate