使用JQuery作为ASP.NET嵌入式Web资源

时间:2009-01-08 12:53:26

标签: asp.net jquery embedded-resource webresource

我有一个ASP.NET服务器控件,它依赖于JQuery来实现某些功能。我试图添加为网络资源。

我的问题是我的方法包括将jquery文件添加到正文中,或者将表单添加到正确的表单中:

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

替代方法是将其添加为head标签中的文字:

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

然而,问题是头部中使用JQuery失败的任何现有代码srcs,因为之后加载了JQuery(ASP.NET在控件树的底部添加了文字)。

是否有一种将JQuery作为嵌入式资源的实用方法,但首先加载到头部?或者我现在应该放弃。

2 个答案:

答案 0 :(得分:7)

如果要打包jQuery并将其嵌入到自己的服务器控件中,则应使用ScriptManager将其提供给客户端。从头到尾你必须:

  1. 将jQuery.js添加到您的项目
  2. 在其“Build Action”属性下, 使其成为嵌入式资源
  3. 你在AssemblyInfo.cs中的
  4. 控制添加

    [assembly: WebResource("<Your Server Control namespace>.jQuery.js", "application/x-javascript")]
    
  5. 让您的控件继承自 System.Web.UI.ScriptControl(或在 至少实施IScriptControl

  6. 覆盖GetScriptReferences:

    protected override IEnumerable<ScriptReference>
    GetScriptReferences()
    {
    return new ScriptReference[] { 
        new ScriptReference("<Your Server Control namespace>.jQuery.js", this.GetType().Assembly.FullName),
    };
    }
    
  7. 您应该在里面设置所有自己的客户端脚本:

    protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()
    

    然后将确保正确的依赖顺序(即jQuery将可用于您自己的客户端脚本)。

答案 1 :(得分:1)

<强>更新

更简单的方法是在脚本中动态添加脚本标记,并指向Google代码托管。 e.g。

function include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

include_dom("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js");

该功能取自this article


Crecentfresh把我推向正确的方向,我也找到了

http://en.csharp-online.net/Creating_Custom_ASP.NET_AJAX_Client_Controls—IScriptControl.GetScriptReferences_Method

我的问题仍然存在,ScriptManager在脚本之后添加引用,但我认为这是一个无法解决的问题。我选择回答自己,但也赞成了crescentfresh。

相关问题