2009-08-20 123 views
1

我有一種情況,我想在我的ScriptManager中引用的js文件(例如「custom.js?2009082020091417」)的路徑中添加「上次修改時間」時間戳(包含在我的母版頁中)和任何ScriptManagerProxies(內容頁面)中。在代碼中訪問ScriptManager代理

我可以很容易地訪問代碼中的ScriptManager,然後遍歷它的Scripts集合來獲取我已經聲明設置的腳本路徑,然後「設置」一個新路徑「?[lastmodifiedtimestamp]」 。

問題是,我無法弄清楚如何到達任何可能存在的ScriptManagerProxies。

調試時,我可以看到非公共成員(._proxies)中的代理。我瀏覽過文檔,無法看到實際公開訪問此集合的位置。

我錯過了什麼嗎?

我在基類我的內容頁面的Page_PreRenderComplete事件的下面的代碼:

ScriptManager sm = ScriptManager.GetCurrent((Page)this); 
if(sm != null) 
{ 
    foreach (ScriptReference sr in sm.Scripts) 
    { 
     string fullpath = Server.MapPath(sr.Path); 
     sr.PathWithVersion(fullpath); //extension method that sets "new" script path 
    } 
} 

上面的代碼給了我一個劇本我已經在我的母版定義的,而不是其他兩個腳本我有在我的內容頁面的ScriptManagerProxy中定義。

回答

4

想出了一個解決方案。似乎唯一可以訪問所有合併腳本的地方在ScriptManager的ResolveScriptReference主事件中。在這種情況下,對於每個具有已定義路徑的腳本,我都會使用一種擴展方法,該方法將根據js文件的上次修改日期來確定「版本號」。現在我的js文件是「版本化」的,當我更改js文件時,瀏覽器不會緩存舊版本。

母版頁編號:

protected void scriptManager_ResolveScriptReference(object sender, ScriptReferenceEventArgs e) 
{ 
    if (!String.IsNullOrEmpty(e.Script.Path)) 
    { 
     e.AddVersionToScriptPath(Server.MapPath(e.Script.Path)); 
    } 
} 

擴展方法:

public static void AddVersionToScriptPath(this ScriptReferenceEventArgs scrArg, string fullpath) 
{ 
     string scriptpath = scrArg.Script.Path; 

     if (File.Exists(fullpath)) 
     { 
      FileInfo fi = new FileInfo(fullpath); 
      scriptpath += "?" + fi.LastWriteTime.ToString("yyyyMMddhhmm"); 
     } 

     scrArg.Script.Path = scriptpath; 
} 
+0

作品像JS魅力,但怎麼做(?會)你處理與你的Javascript(如CSS相關WebResource文件,圖像等)? – jerhewet 2011-08-17 23:32:52