简体   繁体   English

如何在DetailsView ItemTemplate中有条件地显示/隐藏链接

[英]how to conditionally show/hide link in DetailsView ItemTemplate

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. 我是ASP.NET的新手,我试图弄清楚如果值不为null或空白,如何仅在.aspx文件中显示代码块。 Here's what I have, within a DetailsView : 这是我在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. 我想有条件地隐藏整个a标签,如果Eval("Phone")为空或空白。 I would prefer to do this all in the markup, as opposed to doing something in the code-behind. 我宁愿在标记中完成所有操作,而不是在背后的代码中进行操作。

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>

First, change it to an ASP:Hyperlink control. 首先,将其更改为ASP:Hyperlink控件。 The html A tag doesn't have a nive convenient Visible property like the ASP:Hyperlink control does. html A标签没有像ASP:Hyperlink控件那样方便的Visible属性。

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() == "" %>' />

I am afraid you can't do the conditional if within an eval statement. 恐怕如果在eval语句中,您将无法执行条件操作。 Instead, just wrap the simple eval with the function but To handle this situation i usually add a method called NullHandler(). 取而代之的是,只用函数包装简单的eval,但是要处理这种情况,我通常添加一个称为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. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM