Wednesday, October 13, 2010

Expose Child Control In A Custom User Control For Javascript

Hit upon a javascript requirement. I have two controls on my page - a textbox control and a custom user control. The custom user control itself hosts two textboxes. The requirement wanted me to set the value of the standalone textbox control on one of the two inside textbox controls. Came up with two solutions

The unelegant one first - Add an attribute in the hosting page load to handle the blur event of the standalone textbox triggering a __doPostBack. In the load event of the custom user control, adding code to use the FindControl function on the parent page to retrieve the standalone textbox's value and store this in the inside textbox.
While this did the task, the actual postback of the page was a real spoiler (especially since my page had more than just these two items).

Relooked at the same issue a while back and thought of another solution.
An elegant one - Expose the inside textbox as a property of the usercontrol. In the hosting page, add an attribute to handle the blur event, this time however use a simple javascript to set the value of the textbox exposed as a property to the value of the standalone textbox.
Consider the standalone textbox is called txt1 and the usercontrol uc1 has two textboxes - txt2 and txt3. We want to set the value of txt3 to be the same as txt1. We have now exposed txt3 as a property of uc1 say txt3TextBox

In code,
Dim blurJS As String = String.Format(document.getElementByID('{0}').value = document.getElementByID('{1}').value, uc1.txt3TextBox.ClientID, txt1.ClientID)
txt1.Attributes.Add("OnBlur", blurJS)

Well, I had more fun than I added here especially with the txt3 control being part of a view of the multiview and hence I needed to add more checks to ensure that the left hand side of the expression was not null and such. But that is another story.