how to conditionally show/hide link in DetailsView ItemTemplate

ぐ巨炮叔叔 提交于 2020-01-06 20:15:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!