c#
  • asp.net
  • javascript
  • include
  • 2009-08-21 30 views 2 likes 
    2

    我有兩個項目,一個是控制庫,另一個是我的主要項目。從控制庫我目前正在使用用戶控件和一些嵌入在控制庫中的css文件。ASP.Net - 如何從另一個項目中包含嵌入式JavaScript文件?

    我可以做使用嵌入的CSS文件中我的主要項目從我的用戶控件的PreRender事件如下:

    // Register the default CSS resource 
        string includeTemplate = "<link rel='stylesheet' text='text/css' href='{0}' />"; 
        string includeLocation = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "MyCompany.ControlLibrary.WebNotify.WebNotify.css"); 
        LiteralControl cssInclude = new LiteralControl(String.Format(includeTemplate, includeLocation)); 
        ((System.Web.UI.HtmlControls.HtmlHead)Page.Header).Controls.Add(cssInclude); 
    

    我認爲那將是有意義的包括以類似的方式我所有的JavaScript文件,所以我包括嵌入的JavaScript文件執行以下操作:現在

    // Register the js 
        string includeTemplate = "<script type='text/javascript' src='{0}'></script>"; 
        string includeLocation = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "MyCompany.ControlLibrary.Scripts.MyScript.js"); 
        LiteralControl jsInclude = new LiteralControl(String.Format(includeTemplate, includeLocation)); 
        ((System.Web.UI.HtmlControls.HtmlHead)Page.Header).Controls.Add(jsInclude); 
    

    ,CSS的所有作品完美,但我的JS函數試圖打電話給他們時,拋出必選對象的異常。

    我正在以正確的方式去解決這個問題嗎?或者是否有更好的方法將另一個程序集中的嵌入式js文件包含到另一個項目中?

    +1

    什麼是對JS文件響應狀態代碼樣子的要求? 404? 500? – BigBlondeViking 2009-08-21 15:57:43

    +0

    對不起,你的意思是? – GenericTypeTea 2009-08-21 15:59:47

    +0

    如果您正在運行Firefox,請安裝FireBug(http://getfirebug.com),瀏覽到您的站點以及FireBug的腳本選項卡,檢查腳本調用的響應和輸出是什麼。如果您正在運行IE8,請按F12調出開發人員工具,然後在該處查看腳本。 – 2009-08-24 10:46:20

    回答

    3

    就像其他人建議的那樣,使用一些工具,如Firefox的FireBugFiddler或Internet Explorer的開發工具來檢查正在對您的服務器進行哪些調用,以及他們回覆哪些響應 - 這就是BigBlondeViking提到的是什麼

    我還會檢查你是否已經將JS文件標記爲「build」解決方案 - 而不是默認的「不採取行動」。

    然而,的確有增加的嵌入腳本resouces更清潔的方式,ClientScriptManager的「RegisterClientScriptResource」的方法:

    // Get a ClientScriptManager reference from the Page class. 
    ClientScriptManager cs = Page.ClientScript; 
    
    // Register the client resource with the page. 
    cs.RegisterClientScriptResource(rstype, 
        "MyCompany.ControlLibrary.Scripts.MyScript.js"); 
    
    +0

    謝謝,工作很好。 – GenericTypeTea 2009-08-24 14:35:17

    +0

    沒問題,很高興幫助:) – 2009-08-24 15:27:31

    3

    似乎很好;然而,在這一點上,我真的會使用客戶端工具來確定是否所有東西都到達那裏並被使用(fiddler/ie toolbar/firebug/etc)。

    如果我不得不猜測,我會說你的代碼正在工作,但無論你使用什麼瀏覽器,都會忽略JavaScript,因爲腳本標記沒有結束標記(例如<script></script> opposed to <script />);由於某些瀏覽器挑剔的原因

    +1

    +1爲提琴手/螢火蟲 – BigBlondeViking 2009-08-21 15:55:01

    +0

    我改變腳本標籤根據您的建議,我突然意識到我做錯了......但是,這並沒有解決它。 – GenericTypeTea 2009-08-21 16:00:22

    相關問題