ASP.NET 2.0 does great things but like its ancestors also has holes: things we need to do but can't -- or can't without dodging around it with inside knowledge, JScript and other tricks. AspNet2Holes is about those holes and the ways to step around them.

Sunday, June 18, 2006

Events in the life of a page

In its cute fashion, Microsoft discourages application programmers from combining JavaScript with most ASP.NET programming, while making frequent use of the very same JavaScript in the HTML markups that it renders for ASP.NET pages, as a look at the source for many such pages will show. Microsoft does not worry itself with telling you about attributes available for controls in the Source (or markup) view of .aspx files. What you get from them is just a description of server-side classes. Of course Microsoft has all this knowledge well organized and documented. They just don't let you know. If you use the < asp: > elements on a page, as you nearly must to take best advantage of the tools, how do you respond to events on the client side?

The quick answer is that you put them in, just as though you were writing HTML as you otherwise might. For example:

The tools will bark at you, "Warning...Validation (ASP.Net): Attribute 'OnChange' is not a valid attribute of element 'DropDownList'." However, they will copy what you gave them to the HTML markup they produce, resulting in:

When you add a corresponding JavaScript function to the .aspx markup, it will be called as you would expect on a change to the selection for the ofTextHour element.

Microsoft's official approach to supporting client-side events, as one might expect, requires server-side code. Each control has a server-side Attributes property that is an AttributeCollection object with an Add function to add pairs of strings. For the example shown, the code usually placed in Page_Load() would be:

ofTextHour.Attributes.Add("OnChange", "TimeExtender()");

Of course this breaks Microsoft's widely touted "declarative" paradigm. If you take the official approach, you can't see all the attributes of a control in one place. Some server properties are supported in markup, however. This one might have been:

< Attributes > < Add OnChange="TimeExtender()" / > < /Attributes >

Not so, unfortunately, and the above markup will stop the build.

[Note: because of display limitations, characters "< " and " >" here are shown with a space after or before them.]

About Me

Craig BolonCommercial software development over 25 years in Windows and Linux, before that in DOS, Unix, VMS and several others, more than 20 languages. Working now mostly in ASP.NET with C#, SQL and JavaScript.
View my complete profile