How to dynamically change the visibility of html <a> tag in asp.net
I w开发者_运维问答ant to hide an anchor tag based on the value of session object. How am I suppose to do it?
Assuming you wish to do it on server side - the code will be something such as
<a id="MyLink" runat="server" ...
MyLink.Visible = Convert.ToBoolean(Session["MyKey"]);
Note runat="server"
in the markup(aspx) file which is important to refer the control in code-behind.
Add ID
and runat
attributes to the anchor:
<a id="anchor" runat="server"></a>
Set visibility in the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
anchor.Visible = (bool)Session["showAnchor"];
}
As Alex above, but for neatness I tend to put the visibility code inside the aspx tag if it isn't too long, like:
<a id="aid" runat="server" href="link" Visible='<%# (Session["value"] != null) ? Session["value"] : bool.Parse("false") %>' >Text</a>
Haven't tried with a session yet, but it has worked with codebehind functions and bound values, so I don't see why it shouldn't work with session variable.
On a related note, I haven't managed to pass booleans directly this way, hence the use of bool.Parse(""). Don't understand why it won't work directly, since it works when you use values like Visible='<%# string.IsNullOrEmpty() %>'...
<a id="aid" runat="server" href="link">Text</a>
if (Session["value"] != null)
{
aid.Visible = true;
}
else
{
aid.Visible = false;
}
It depends if you want to hide the link on a postback / initial load or after the page has already been delivered to the client.
If you want to hide the link on postback / initial load, you can add the runat="server" attribute to the link and set its Visible property in the code behind.
If you want to hide the link on a page that is already on the client, you can poll the server with Ajax calls and then hide the link using javascript.
精彩评论