Wednesday, May 25, 2005

.NET and JavaScript

It's kinda like mixing oil and water, except in this case, .NET without JavaScript makes for a terrible user experience. But on the flip side, .NET with JavaScript can keep a programmer up for weeks trying to cope with the troubles that ensue when you start adding custom JavaScript to .NET pages.

Take these past couple of days, for instance. I created this custom server control for selecting a date. The control was comprised of 3 DropDownList controls, one for the month, one for the day, and one for the year. I created a sample application to test my control, and everything seemed to be fine. Then, I used the control in a much more elaborate project we are developing at work, and the control was broke. Same JavaScript. Same HTML rendered, but now, when the page posts back, the control no longer remembers it's state. I remove the JavaScript calls on the month and year drop downs, and the control remembers its state just fine.

So what's up with that? I began to look at the JavaScript that I was using. It was simple. When the month or year drop-downs changed, I wanted to update the day control so that it only gave valid day choices for the month and year combination. So I thought to myself, maybe something in what I am doing in the JavaScript, even though it works, is causing this broke behavior. So I kept the calls to the JavaScript functions in the drop-down change events, but I removed all of the code in the function, leaving empty functions. The control was still broke in the post-back, not remembering its state.

Then, I began to get creative. I decided to create another control, this time a text input control to house the date defined by the three drop-down inputs. When any of the drop-downs would change, I would put the combined value into the textbox. Once again, though, when the page posted back, the textbox lost its state too. So, I removed the JavaScript calls on the drop-downs, and the textbox remembered its state.

By now, this had gotten too strange for me. So, to keep from wasting any more time, I removed the JavaScript calls, and implemented the code to update the items in the day drop down in the SelectedIndexChanged event of the month and year. All works.

I have yet to figure out what the real cause to the problem is, but the same control used in one web app, worked. Used in a different web app, and it fails. Strange, strange, strange. If anyone would have an idea, let me know.

No comments: