简体   繁体   中英

ASP.NET use Hyperlinks instead of Buttons

I would like to add a Logout link to my form so our employees can log out of the job they are working on.

The code behind in my application is simple:

protected void Logout_Click(object sender, EventArgs e) {
   MasterPage.Logout();
}

A asp.Button I can code by wiring up the onClick event.

How would I call this method using a asp.Hyperlink control?

You're looking for the LinkButton control. That gets rendered as an a tag, and the page will be posted back to itself so that your OnClick function can be invoked.

The Hyperlink control renders a simple hyperlink, which won't allow you to wire it up to a click handler. Try the LinkButton control instead.

Replace Hyperlink with LinkButton. Hyperlink has no server side events. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton.aspx

One thing I might suggest is to simply use CSS to style your actual-fact button to adopt the look of a link, as opposed to imitating a button from something that will likely be styled differently anyway.

When imitating a button, you are relying on the user having script enabled in their browser:

The LinkButton control renders JavaScript to the client browser. The client browser must have JavaScript enabled for this control to function properly.

Whereas a button that is a button will submit the form.

EDIT:

As per your comment, here is a quick example you could easily adapt:

CSS:

.hyperLinkButton
{
    border:none;
    background:none;
    color:Navy;
    cursor:pointer;
}
.hyperLinkButton:hover
{
    text-decoration:underline;
}

Mark-up:

<asp:Button runat="server" CssClass="hyperLinkButton" 
  Text="Is it a HyperLink? Is it a LinkButton? No, it's a Button!" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM