Yalda
Yalda

Reputation: 684

How to set a link's NavigateUrl on link onClick?

I'm creating a link dynamically. The NavigateUrlproperty of the link is set on a call to a method. But I don't want to call the method before the link is clicked because there are so many of such links.

Any help on how to do it is appreciated. Thanks.

public void CreateLink()
{
   LinkButton link = new LinkButton();
   link.Click += new EventHandler(link_Click);
   string key = GetKey();
}

private void link_Click(object sender, EventArgs e)
{
    var url = GetLinkUrl(e.???);
    Response.Redirect(url);       
}


public string GetLinkUrl(string key)
{
    //do things to retrieve url
    return url;
}

Update: Many thanks, all :) I am going to use LinkButton, as seen in updated code above. But I forgot to ask: There is a key associated with each link which is needed to get the URL. How can I

Upvotes: 1

Views: 4727

Answers (2)

Adrian Wragg
Adrian Wragg

Reputation: 7401

What you're doing is potentially quite complex; you would need to output back to the client something indicating a call to a code-behind method to be executed before the navigation occurs, for example:

HyperLink link = new HyperLink();
link.Attributes.Add("onclick", "doClientsideCode();");
...

Then, a bit of JavaScript:

function doClientsideCode() {
    // Do a call to a service or similar, to run the method you're wanting to run.
    // This will then do the navigation you require.
}

Thus, my suggestion would actually be a LinkButton; this will fire an event that you can capture server-side, via something similar to:

public void link_Click(object sender, EventArgs e) {
    // Run my method
    // Issue response.redirect to correct URL.
}

[Edit - in answer to the edited question, you have access to the properties CommandName and CommandArgument when using a LinkButton which should do what you require. However, I do feel that that part should now be a separate question.]

Upvotes: 4

Katstevens
Katstevens

Reputation: 1571

One alternative is to use an ASP button instead of Hyperlink, and bind the GetLinkUrl function inside a click handler for the button. Then run Response.Redirect('yourURL') to execute the link.

EDIT: As Adrian said above, a LinkButton will be the best of both worlds - it is styled like a Hyperlink, but you can set a click handler for it to get the URL dynamically, only when the button is actually clicked.

Upvotes: 3

Related Questions