views:

60

answers:

1

Ok, I'm making a couple of JQuery versions of the AJAXToolkit controls (we were having issues with the toolkit), and want to have a common version of the scripts they require on the page.

To do this, I was intending to have a JQueryControlManager control, and use it to insert scripts dynamically, preferably only scripts that are needed by controls on the page.

Does anyone know of an efficient way to:

  • Check a ControlManager control exists on the page if some other JQueryControls do
  • Add each control to a collection within the ControlManager, assuming the answer to the first point does not return the JQueryControlManager instance

OR

Does anyone have a suggestion for a better solution?

+1  A: 

For scripts specifically, ASP.NET already has a nice ScriptManager class that supports what you're trying to do. Call

Page.ClientScript.RegisterClientScriptInclude(key, url);

from your control with a unique key for each script and the framework will take care of avoiding duplicates. There are other similar methods on ClientScriptManager that may be useful.

If you still need to create an instance of your ControlManager you could either just enumerate over the Page.Controls collection looking for a control of that type, ie.

public ControlManager GetControlManager()
{
    foreach (Control control in Page.Controls)
    {
        if (control is ControlManager)
            return (ControlManager)control;
    }

    ControlManager manager = new ControlManager();
    Page.Controls.Add(manager);

    return manager;
}

or you could try storing the instance of ControlManager in the Page.Items dictionary.

Warning: I haven't tested this code, so treat it as pseudo-code.

Evgeny
Using Scriptmanager isn't really what I'm going for: I'm planning to do some clever stuff with which scripts are imported, and with the $(function() {}); As for iterating over the Page.Controls, this is horribly inefficient (also, Page.Controls needs to be iterated recursively), and a bit of a pain when you've got ~50 of the related controls on the page! Page.Items might work though...
Ed Woodcock
Yeah, if performance is an issue then Page.Items would be better. I'm not sure that you'd have needed to iterate recursively, though - are you going to have multiple of these ControlManagers on one page at different levels in the control hierarchy?
Evgeny
Well, you need recursion unless it's on the very top level of the page, so if you're using a masterpage there can be issues. I'm going with Page.Items[typeof(ControlManager)], that's how the scriptmanager does it, so I guess it's the best option.
Ed Woodcock