0

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?

5 Answers 5

3

Try:

<a href="javascript:document.getElementById('<%= logout.ClientID %>').click();" class="top">Log Out</a>
Sign up to request clarification or add additional context in comments.

3 Comments

Not enough.. there will be no button in the HTML source code because the server won't send anything due to the button having Visible="false"
@shadow is correct when page gets rendered browser will not be getting any element , i think you can use ajax to make a partial post back and call a server side function.
@ankur really no need for AJAX here - the accepted answer is what needed.
2

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

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

1 Comment

Not really enough.. you better not rely the ID will be the final client ID and use <%= logout.ClientID %> to get it.
0

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

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

Comments

0

Or you can use the __doPostBack function ...

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.