2009-12-17 42 views
0

有人可以看下面的代碼並告訴我我做錯了什麼。由ScriptManager.RegisterStartupScript調用的客戶端方法不能觸發

for(i=0;i<=Request.Files.Count;i++) 
{ 

int percentComplete = (int)Math.Ceiling((double)(i + 1)/(double)Request.Files.Count * 100); 
string message = string.Format("{0} of {1} uploaded", i + 1, Request.Files.Count); 

ScriptManager.RegisterStartupScript(this, this.GetType(), "progress", @"do_progress("+message+","+percentComplete+");", true); 

} 

我正在嘗試每次循環更新客戶端。在客戶端(在表單標籤內),我有一個名爲「do_progress」的函數,它帶有兩個參數:message和percent。我的意圖是,客戶端方法隨着循環的每個循環而激發,但沒有任何反應。

UPDATE

感謝您的幫助。 Ramiz,你的代碼在我的情況下不起作用,因爲它收集循環內的所有方法(和進度),然後同時將它們發送給客戶端。 這不會準確顯示進度(每個循環代表已上傳文件的完成情況)。我需要在服務器端循環的每次唯一完成之後訪問客戶端函數do_progress。

此外,頁面已經加載,並在單擊(上傳)按鈕時的代碼被激發。

話雖如此,我仍然有問題。我可以證實,我通過看「選擇來源」得到我想用下面的代碼的結果:

int percentComplete = (int)Math.Ceiling((double)(i + 1)/(double)Request.Files.Count * 100); 

string message = string.Format("{0} of {1} uploaded", i + 1, Request.Files.Count); 

ScriptManager.RegisterStartupScript(this, this.GetType(), "progress" + i, @"do_progress('" + message + "','" + percentComplete + "');", true); 

但是,我沒有看到實時的客戶端上的結果更新。進度條不移動,計數器(n個文件中的n個)沒有任何操作。但是,當我看着innerHTML時,值已經更新了。很奇怪。這幾乎就像我需要刷新頁面或其他東西,但這不應該是必要的。

客戶端功能我用的,這是擺在表單標籤頁面的最後,是這樣的:

function do_progress(message,percent) 
        { 
         try { 
          $('progress_status').innerHTML = message; 
          $('progress_bar').attr("style", percent + "px"); 
         }catch(e){alert(e.message)}; 
        } 
+0

嘗試RegisterClientScriptBlock而不是RegisterStartupScript – 2009-12-17 07:39:20

+0

無論你是要在頁面加載或點擊事件... – 2009-12-17 07:44:08

回答

0

messagestring值應該封閉在單引號"do_progress('"+message+"',"+percentComplete+");"

percentComplete包含integer所以它不需要附上單引號message呢。

string methods = string.empty; 

for(i=0;i<=Request.Files.Count;i++) 
{ 

int percentComplete = (int)Math.Ceiling((double)(i + 1)/(double)Request.Files.Count * 100); 
string message = string.Format("{0} of {1} uploaded", i + 1, Request.Files.Count); 

methods += "do_progress('"+message+"','"+percentComplete+"');" 

} 

其次,在這裏,我遞增的所有方法在string變量,把它在window.onload事件只是確保DOM準備就緒,我們稱之爲do_progress功能之前。

ScriptManager.RegisterStartupScript(this, this.GetType(), "progress", @"window.onload = function() {"+ methods +"}", true); 

但是,這不應該要求在這裏,在window.onload調用爲ScriptManager.RegisterStartupScript會叫他們時DOM準備好。

我不確定到底是什麼問題,但這是我的即時審查。

+0

謝謝,我已經更新了我的問題作出迴應... – 2009-12-17 19:52:33

0

嘗試使用,而不是ScriptManager.RegisterStartupScript

+0

謝謝,我試過了,但它似乎並不重要 – 2009-12-17 20:15:40

0

你的客戶端do_progress功能似乎有一個錯誤在jQuery選擇this.RegisterStartupScript - 你目前正在尋找元素命名progress_statusprogress_bar當我懷疑你打算尋找課程或ID。如果你的選擇器不匹配任何東西,它不會引發任何錯誤,它只是不會做任何事情。