views:

2203

answers:

6

Is there a way to click a link programatically, so that it has the same effects as if the user clicked on it?

Example:

I have an ASP.NET LinkButton:

<asp:LinkButton id="lnkExport" runat="server" CssClass="navclass">Export</asp:LinkButton>

I have a link on a sidebar directing to the .aspx page that has this linkbutton on it. For various reasons I can't have the code for the LinkButton executed until the page has refreshed -- so I am looking for a way to force-click this LinkButton in my code once the page is completely loaded. Is there a simple/doable way to accomplish this? If it involves triggering an event, please provide a code sample if you can. Thanks.

A: 

I'm not sure why you'd need your page to load if you're just wanting to programmatically click that link. I'd recommend using Response.Redirect() on the server side to redirect them to that page. Not sure if there are other extenuating reasons this simple approach won't work...

--Matt

Matthew Timbs
A: 

Triggering a click event programatically on a link will trigger the “onclick” event, but not the default action(href).

And since linkbuttons come out as hrefs, so you could try doing this with Javascript.

var lnkExport = document.getElementById('<%= lnkExport.ClientID %>');
if(lnkExport){
   window.location = lnkExport.href;
}
Dhana
A: 
<button onclick="document.getElementById('<%=this.lnkExport.ClienID%>').click()">
 click me</button>
Rashack
A: 

If i understand what you're saying:

<asp:LinkButton id="lnkExport" runat="server" CssClass="navclass" onclick="lnkExport_Click">Export</asp:LinkButton>

then in your codebehind or whenever call the following when you need to...

lnkExport_Click( null, null );

and make sure you've got lnkExport_Click wired up.

protected void lnkExport_Click( object sender, EventArgs e )
{
//DO Whatever here
}
Blake
+1  A: 

I certainly think that, there is a design and implementation flaw which forces you to conclude as you described.

Well, invoking the click event means nothing but executing the event registration method.

So, the worst suggestion I can think of is, just call the function at what point you want to happen the click event like,

lnkExport_Click(lnkExport, new EventArgs());

123Developer
A: 

Rashack's post show's how to do it. You can just do it in javascript.


function ClickLink() {
  document.getElementById('').click();
}

If you want this to fire after some other event, you can add code in c# to add a call to that function on the client side when the page loads.


Page.ClientScript.RegisterStartupScript(
  this.getType(), 
  "clickLink", 
  "ClickLink();",
  true);
Scott Nichols
This works to click the link but didn't solve the problem I had. ultimately I don't think there's a direct solution to it -- but I found that if you open a new dialog box with the downloaded file linked to it, it works almost as well (except for the extra dialog window which has to be closed).
n2009