当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - ASP.NET 2.0 - Need to programmatically click a link

问题描述:

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.

网友答案:

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);
网友答案:

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;
}
网友答案:

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());

网友答案:

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

网友答案:

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
}
网友答案:
<button onclick="document.getElementById('<%=this.lnkExport.ClienID%>').click()">
 click me</button>
分享给朋友:
您可能感兴趣的文章:
随机阅读: