views:

28

answers:

4

Hello,

I have a label and I want to add to it a link.

I want to use javascript like :

MyLabel.Attributes.Add("`onclick`", "javascript:`SOME_CODE`")

What must I add in (SOME_CODE) to redirect the user to another link.

Thanks.

+2  A: 

Have you tried: window.location = 'http://google.com' ? Are the any particular reason you want to use Javascript for this, and not just the HyperLink Control?

Update:

You can either use a normal a-tag <a href="http://google.com"&gt;link&lt;/a&gt; or use the ASP.Net HyperLink control:

This is the markup:

<asp:HyperLink ID="MyHyperLinkControl" NavigateUrl="http://google.com" runat="server" />

This is if you want to add it from the code-behind:

HyperLink link = new HyperLink();
link.NavigateUrl = "http://google.com";

parentControl.Controls.Add(link);

Where parentControl, is the container you want to add it to, for instance a cell in a table or a panel.

See here for more information on how to add a control to a panel

Arkain
It's working. But how can I use HyperLink Control ?
dotNET
I think `window.location.href` is more reliable than `window.location` between different types of browsers.
Paperjam
@Paperjam, you are right window.location.href would be the more correct one because window.location is basically the object containing other properties, among them href. window.location can however be used as a shorthand for window.location.href.
Arkain
A: 
<a href="http://google.com" >Go to Google</a>
Oleg Kalenbet
A: 

Just use a plain anchor tag (<a >), but put the label inside the anchor (the reverse is not strictly valid html). If you don't want it to show up as a link every time, you can accomplish that by omitting the href attribute. This is easy to do with a normal <asp:HyperLink> server control like so:

<asp:HyperLink id="..." runat="server"><asp:Label ... ></asp:Label></asp:HyperLink>

Now, the href attribute will only render if you actually set the NavigateUrl property in your code. You might also find that using an <asp:HyperLink> completely replaces the need for the label.

Joel Coehoorn
A: 

If this has anything to do with your previous question, use a Hyperlink control instead of a Label:

    Dim Hyperlink1 As New Hyperlink
    Hyperlink1.Text = "XYZ"
    Hyperlink1.NavigateUrl = "http://www.google.com"

    Dim Literal1 As New Literal
    Literal1.Text = "<br />"

    ' Add the control to the placeholder
    PlaceHolder1.Controls.Add(Hyperlink1)
    PlaceHolder1.Controls.Add(Literal1)
Paperjam