Search code examples
.netjquerycustom-server-controls

How to embed JQuery into custom server control


I am writing a server control that is a search box with suggestions (when the user starts typing, matching words will appear for them to select). I am using jquery and C#.

The control works fine when I include the jquery Lib on the page that I am testing on. However, it will not work when I attempt to embed the lib in the DLL.

I have tried completely embedding it and registering the script:

ClientScriptManager manager = this.Page.ClientScript;
manager.RegisterClientScriptResource(typeof(Search), jqueryResource); //jqueryResource= SearchControl.javascript.jquery.js 

and I am also tried just adding a tag in the header of the page that includes the jquery:

string javascriptUrl = manager.GetWebResourceUrl(typeof(Search), jqueryResource); 
LiteralControl jquery = new LiteralControl(string.Format(javascriptInclude, jqueryUrl));
Page.Header.Controls.Add(jquery);

Both ways cause javascript errors (Object Expected) when trying to get information from controls

var params = $("#searchBox").val(); //called on keyup when typing in textbox

Has someone done this before? Is it possible? Can someone shed some light on this?

PS: Assemblies are already registered in the AssemblyInfo.cs file.


Solution

  • EDIT: Just re-read your question and realised I've just repeated what you've done. However this is my implementation which works as expected:

    You need to use RegisterClientScriptResource. Just call the following snippet (taken from my ScriptRegisterHelper static class) in the PreRender event of the control:

    /// <summary>
    /// Registers the jQuery client script to the page.
    /// </summary>
    /// <param name="cs">The ClientScriptManager to assign the script to.</param>
    internal static void RegisterJQuery(ClientScriptManager cs)
    {
        cs.RegisterClientScriptResource(typeof(ScriptRegisterHelper), 
            "MyProject.Resources.jquery.js");
    }
    

    And for completion, here's the implentation:

    protected override void OnPreRender(EventArgs e)
    {
        if (!this.DesignMode)
        {
    
           // Register the JavaScript libraries
           ClientScriptManager cs = this.Page.ClientScript;
           ScriptRegisterHelper.RegisterJQuery(cs);
    
        }
    }
    

    And the AssemblyInfo file:

    [assembly: System.Web.UI.WebResource("MyProject.Resources.jquery.js", "text/javascript")]