Sunday, October 2, 2005

Anchor onclick vs. Href

[This was originally posted at]

ASPX, including all its "special" features like postbacks and validators, ultimately renders as standard Html. So it's good to understand how certain Html components, like anchors, work.

A simple anchor just has an target page in the Href, look like so:


Clicking this anchor will always redirect to PageB.aspx. The Href property can also contain a method to call. For example, ASP.Net renders LinkButtons as anchors whose Href calls the postback method:


Anchors can also have an onclick event. You could have this method call a message box, set hidden fields, or do whatever else you needed. However, the Href will not be called if the onclick returns false. For example, you could create a "Do you want to save?" yes-no MessageBox like so:


The JavaScript confirm() method displays a yes-no confirm box, and returns either true or false depending on what the user clicked. Therefore if the user clicks no, the messageBox returns false, and the href is never activated. This concept applies whether the Href contains a navigation page or JavaScript. For example, you could add the confirm box to the LinkButton, and block the postback if the user answered "No" to a certain question.

Knowing the relationship between the anchor onclick and href lets you develop a more interactive and rich UI.

No comments:

Post a Comment