views:

1080

answers:

2

I have an ASP.NET server control which relies on JQuery for certain functionality. I've tried to add as a webresource.

My problem is my method of including the jquery file adds it to the body, or the form to be exact:

this.Page.ClientScript.RegisterClientScriptInclude(...)

The alternative to this is to add it as a literal in the head tag:

LiteralControl include = new LiteralControl(jslink);
this.Page.Header.Controls.Add(include);

The problem with this however is any existing code srcs in the head which use JQuery fail, as JQuery is loaded afterwards (ASP.NET adds the literal at the bottom of the control tree).

Is there a practical way of making JQuery an embedded resource, but loaded in the head first? Or should I give up now.

+4  A: 

If you want to package up jQuery and embed it inside your own server control you should serve it to the client using the ScriptManager. From the top of my head you have to:

  1. add jQuery.js to your project
  2. under its "Build Action" Property, make it an Embedded Resource
  3. in the AssemblyInfo.cs for your control add

    [assembly: WebResource("<Your Server Control namespace>.jQuery.js", "application/x-javascript")]
    
  4. Make your control inherit from System.Web.UI.ScriptControl (or at least implement IScriptControl)

  5. Override GetScriptReferences:

    protected override IEnumerable<ScriptReference>
    GetScriptReferences()
    {
    return new ScriptReference[] { 
     new ScriptReference("<Your Server Control namespace>.jQuery.js", this.GetType().Assembly.FullName),
    };
    }
    

All of your own client script should be setup inside:

protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()

Which will then ensure the correct order of dependencies (ie jQuery will be available to your own client script).

Crescent Fresh
Oh, and you should probably use jQuery noConflict() and expose it inside your own client-side namespace. IE MyNameSpace.$ = jQuery.noConflict()So as not to interfere with other uses of $ the outer page might be doing.
Crescent Fresh
I have to try that, we've had the same issue.
GoodEnough
This has pushed me in the right direction, I also found http://en.csharp-online.net/Creating_Custom_ASP.NET_AJAX_Client_Controls—IScriptControl.GetScriptReferences_Method .My problem still remains though, the ScriptManager adds the references after the script in the head.
Chris S
+1  A: 
Chris S