AlexMorley-Finch
AlexMorley-Finch

Reputation: 6955

href link to trigger asp.net c# button event

I have a navigation bar consisting of list items. Right at the end of the nav bar I want a logout link:

//other links

...

<li>
    <a href="#"> logout </a>
</li>

I have an event in my C# code called Logout_Click(object sender, EventArgs e) that I want to run when the user clicks the above navbar link, but obviously ordinary <a> tags don't trigger ASP.NET click events.

So I thought I'd be clever and create a HIDDEN <asp:Button> called logout that does trigger the Logout_Click function, and then get the JavaScript to click the button for me.. here is my code:

<a href="javascript:document.getElementById('logout').click();" class="top">Log Out</a>

<form runat="server">
    <asp:Button ID="logout" runat="server" onclick="Logout_Click" Visible="false" />
</form>

But it still didn't work.

Can someone help me?

Upvotes: 0

Views: 3547

Answers (5)

Waqar Janjua
Waqar Janjua

Reputation: 6123

Why not you are using Asp.net LinkButton ? It's easy to do this work with LinkButton.

Upvotes: 0

2GDev
2GDev

Reputation: 2466

Or you can use the __doPostBack function ...

http://wiki.asp.net/page.aspx/1082/dopostback-function/enter link description here

Upvotes: 0

Matt Evans
Matt Evans

Reputation: 7575

I think the script needs the client side id of your asp.net control:

javascript:document.getElementById('<%=logout.ClientID').click()

Upvotes: 0

robertc
robertc

Reputation: 75707

Try:

<a href="javascript:document.getElementById('<%= logout.ClientID %>').click();" class="top">Log Out</a>

Upvotes: 4

joaofilipe
joaofilipe

Reputation: 64

Can you try without the Visible="false" on the asp:button?

And if it works hide it with css instead, style="display:none;"

Upvotes: 3

Related Questions