Saturday, July 15, 2006

.Net: The dark side clouds everything

The past week at work I spent some time reimplementing one of our more complicated, multi-page, multi-function, high-profile portlets using sharpdevelop/web matrix. I'm getting better at the mere mechanics of the conversion, replacing former items in the page template with asp controls and moving code from former actions to page_load and onclick handlers.

The interesting wrinkle this time was a page that has a dynamic form. Not only are the choices different for each category of user, but even the categories of those choices are different. Meaning that the form has a variable number of inputs; in fact, the form is data driven. Of course, adding new inputs would require a change in code, but the order of the form's existing inputs could be rearranged just by modifying an 'ord' field in a database table.

The difficulty is not dynamically creating the inputs, but getting the values from the inputs back out again the next time the form is submitted. Before .Net, I did this by assigning the correct HTML 'name' attribute to each input as it was dynamically created inside the 'repeat' tag's template. Getting the values out on submit was just a matter of keying into the request's form inputs with the relevant name. In .Net, setting the 'name' attribute on an asp control to whatever the hell you want won't work, and it might even mess up its VIEWSTATE processing (the part that automatically keeps track of the current state of all inputs on the page). The control innocently named inside the repeater template receives a new, menacing name once it falls under the Dark influence. So how does one know that the value for data item 'farg3' is in the dynamically generated dropdownlist control with id '&4745_ct100_5'?

I wrote a handler for the ItemDataBound event for the repeater in which the uniqueID property for that generated input goes in the view state bag keyed by the data item name that input was genereated for. Then, when I need the value for a particular data item, I get the uniqueID from the view state bag, start at the repeater control, and recursively search for the input control with that uniqueID. Uuuuuugly, the elegance of recusion notwithstanding, but it seems to work in my tests so far. I bet that there was easier way to accomplish this, but I just didn't know it or find it. Sometimes I like that the .Net controls just sit on the page and handle the details of how they look, but only as long as they take direction like an agreeable actor and not like, well, Brando. I don't have a page any more to work with, but a hierarchy of controls. In this case, that worked against me, because I had trouble seeing the individual value I wanted to inside the shroud. In other words, sometimes the dark side clouds everything.

No comments:

Post a Comment