views:

674

answers:

4

Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls? Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control. Adding it during the Page_Load event through codebehind works, but is less clear than I'd like.

Are these the only two choices? Is there a right way to do this that I'm missing?

Thanks! Eric Sipple

+1  A: 

Setting the value for WebControl.Attributes["onclick"] is okay. If ASP.NET needs a client-side click handler, it will concatenate the values, delimited by semi-colon.

Mark Cidade
+2  A: 

**just a pre-note on the answer: HTML validation in VS is often BS. It complains about stuff that works IRL, even if that stuff is bad practice. But sometimes you gotta bend the rules to get stuff done.

Every ASP.NET page (2.0 and greater) comes with a ClientScriptManager. You use this to register javascript from server side code. You can pass in javascript that registers events on controls after the page has loaded, when the HTML controls on the page are all present in the DOM.

It presents a single, unified place on pages to dynamically add javascript, which isn't a bad thing. It is, however, awfully ugly.

In this time of the death of the ASP.NET server control model, you might want to set events the way they will be in the future of ASP.NET MVC. Grab a copy of jQuery and add it to your website. You can then easily register your events thusly:

  <html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $("controlId").bind("click", function(e) { /* do your best here! */ });
      });
    </script>
  </head>
  <!-- etc -->
  </html>
Will
+2  A: 

You can add the events through Javascript to the HTML elements that you want. This is the cleanest way, since it doesn't mix the server&client technologies. Furthermore, this way many handlers can be registered to the same event (in contrast to the onclick attribute).

Basically, the code would be

document.getElementById('myLovelyButtonId').attachEvent('onclick',doSomething)

for Internet Explorer and

document.getElementById('myLovelyButtonId').addEventListener('click',doSomething,false)

for other browsers. (doSomething is an event handler - JavaScript function). These calls should be made in the window load event handler

Consider reading the advanced event registration article on Quirksmode for further info.

Also, consider using a library like jQuery. This way, the statement will become

$('#myLovelyButtonId').click(
    function doSomething () {
        alert('my lovely code here');
    });
Alexander Gyoshev
A: 

Fix grammatical or spelling errors.

Clarify meaning without changing it.

Correct minor mistakes.

Add related resources or links.

Always respect the original author.