- Master Page
- Child Page
- User Control
- ASP.Net control
This is simple – multiple stacks of child pages user controls etc.. are possible and I certainly use them all the time.
What surprised me when I started doing this was the effect it had on the element Ids as exposed to JavaScript. I printed off one such example this week – an id of a dropdown list.
ctl00_ContentPlaceHolder1_dashboardMain_ddlOrganisation
Mmmmm – but I thought I’d just called it ddlOrganisation. Apparently not. The breakdown is
- ct100 – from the master page
- ContentPlaceHolder1 – from the child page (hold my hand up for this – it’s a rubbish name)
- dashboardMain – the user control
- ddlOrganisation – my control that I want to target.
OK, fine. Lots of under the hood .Net stuff going on. But it confused the hell out of me when I wanted to target this stuff in the Javascript DOM. Once you figure out the ID then you could just use it. But any change in the names of your controls higher up in the hierarchy will break it. And it will break it 5.00 p.m. on the day before you are due to ship – believe me. A better idea is to use the ClientID property that ASP.Net controls expose. This will provide the Byzantine ID that we see above.
So to add a JavaScript event I would add the JavaScript into the attribute collection of the control within the ASP.Net page – so adding a JavaScript method to the OnSelect event
ddlOrganisation.Attributes.Add("OnChange", "activateSurveyStart('" + ddlOrganisation.ClientID + "')");
And to complete the circle – register the Javascript file programmatically in your usercontrol to avoid tears later
Page.ClientScript.RegisterClientScriptInclude("genericScript", "scripts/genericScript.js");
Not a revolutionary method admittedly (none of my stuff ever will be – promise). But I use this all the time and I think it’s more obscure than it should be. And the making friends thing? Well, be nice to people and bring cakes into your office every Friday. That’ll do the trick
No comments:
Post a Comment